|
|
|
|
|
by timoxley
3003 days 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
|
|
Same behavior on Ruby: