Converting into a Boolean

All values in JavaScript when converted into a Boolean will return true unless they are one of the seven falsy primitives (false, null, undefined, 0n, 0, "", and NaN), in which case they will return false.

To cast a value to a Boolean, we can simply pass the value to the Boolean constructor, invoking it as a function:

Boolean(0); // => falseBoolean(1); // => true

The language will coerce values to Booleans when the values exist in a Boolean context. Here are some examples of such contexts (each marked with HERE):

  • if ( HERE ) {...}
  • do {...} while (HERE)
  • while (HERE) {...}
  • for (...; HERE; ...) {...}
  • [...].filter(function() { return HERE })
  • [...].some(function() { return HERE })

This list is not exhaustive. There ...

Get Clean Code in JavaScript now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.