Truthy and falsy

I don’t propose spending time trying to remember coercion rules. It's all about awareness - then you can test or look up how any expression will behave.

But one set of rules is worth knowing by heart, because you will read it in almost every line of real code.

The falsy values

Anything that needs a true or false value - like the condition of an if() - is coerced to a boolean. These are coerced to false:

false, 0, '' (an empty string), null, undefined and NaN.

Everything else is truthy, including '0', 'false', [] and {}.

That’s why you will see code like this everywhere:

if (user) { /* we have a user */ }

const name = input || 'Anonymous'; // any falsy input -> 'Anonymous'
const count = saved ?? 0;          // only null or undefined -> 0

The || uses the right-hand value when the left is falsy. The ?? only does it when the left is null or undefined - so a real 0 or '' survives.

Links & Resources

  • Anki Review Cardsapps.ankiweb.net