9 ms·
A big gotcha with `&&` as a guard in JS is that it can return any falsey typed value if you don't coerce the guard to a boolean. e.g. const check(cond) =
by timoxley 8y ago
A big gotcha with `&&` as a guard in JS is that it can return any falsey typed value if you don't coerce the guard to a boolean.
e.g.
const check(cond) => cond && otherValue
If `cond` is falsey, it returns `cond`.
This means the function could return any of: `false`, `undefined`, `null`, '', `0` or `NaN`.
This is a fairly common issue I see with React + JSX:
<div>{cond && <SomeComponent />}</div>
If `cond` is `false`, `null`, `undefined` or '', everything will be just fine, but if `cond` happens to be a zero or `NaN`, suddenly you have a weird `0` or `NaN` rendering in your page. Oops.
Low cost, much safer guard:
const check(cond) => !!cond && otherValue
- Waterluvian 8y agoGood point. Good example. I imagine it works well in my cases but I haven't come across cases like your example where it breaks down.
- acjohnson55 8y ago...until you do. That's the problem with antipatterns. It's impossible to remain alert to the edge cases, and then they eventually bite you in production. Better to lint them away. But it's difficult to convince people not to do something really convenient if they haven't gotten bitten yet.
- sgustard 8y agoYes, back when CoffeeScript was in vogue the ? operator handled this case nicely: cond? && otherValue
- sergeykish 8y agoQuite interesting. For a moment I've thought it is another JS issue but no. It's React who's strange https://github.com/facebook/react/blob/v0.11.2/src/browser/ui/ReactDOMComponent.js#L184 https://github.com/facebook/react/blob/v0.11.2/src/browser/u... https://github.com/facebook/react/blob/v0.11.2/src/utils/traverseAllChildren.js#L126 https://github.com/facebook/react/blob/v0.11.2/src/utils/tra... Same behavior on Ruby: def content_markup(children) case children when String, Numeric children when NilClass, TrueClass, FalseClass return else # ... end end content_markup 'foo' #=> "foo" content_markup 0 #=> 0 content_markup true #=> nil content_markup false #=> nil content_markup nil #=> nil