4 ms·
I've also seen code written as: _ = !isDefined(user) && throw new Error("User must be defined."); _ = !isString(user.firstName) && throw new Error("User'
by 0xcoffee 6y ago
I've also seen code written as:
_ = !isDefined(user) && throw new Error("User must be defined.");
_ = !isString(user.firstName) && throw new Error("User's first name must be a string");
But I while it is concise, I can also understand why people prefer regular if statements.
Doesn't seem to be valid JS, can't remember where I got it from
- CloselyChunky 6y agoIn my opinion this pattern is better if you write it like this: _ = isDefined(user) || throw new Error("user must be defined") This reads way more natural for me. "A user is defined OR throw an error"... I've also seen this in Perl (`do_something() || die()`) and shell scripts (`grep -q || die "not found"`).
- pxx 6y agoIn perl you would want to use `or` instead of `||` to take advantage of the low precedence, so you can type things like `dostuff $foo or die` which is logically 'do stuff, and if it fails, die' as opposed to 'die if $foo is false', which you'd get with ||
- lhorie 6y agoIt's a stage 2 proposal, which technically can be used today via babel[0] (though personally, I don't recommend using stuff below stage 4) [0] https://babeljs.io/docs/en/babel-plugin-proposal-throw-expressions https://babeljs.io/docs/en/babel-plugin-proposal-throw-expre...
- IggleSniggle 6y agoMy preference for this is to use an assertion function, eg in nodejs: assert(isDefined(user),”User must be defined”) // throws if Falsy
- d1sxeyes 6y agoThis pattern is quite common in React to do conditional rendering: {isLoading && <Loading />}