/ javascript

List of Falsy Values in JavaScript & ToBoolean Algorithm

Here's a no frills post about the falsy values in JS. In case you didn't know, JavaScript considers some values as truthy and other as falsy. Most are deemed truthy so it's a lot easier to simply remember the falsy ones.

You can see the truthy vs falsy evaluation in action when using an if statement. The statement takes in an expression and coerces it to a boolean value using the ToBoolean algorithm. The result is predictable and outlined in the table provided by the ECMAScript spec. Here it is below:

Argument Type Result
Completion Record If argument is an abrupt completion, return argument. Otherwise return ToBoolean(argument.[[value]]).
Undefined Return false.
Null Return false.
Boolean Return argument.
Number Return false if argument is +0, −0, or NaN; otherwise return true.
String Return false if argument is the empty String (its length is zero); otherwise return true.
Symbol Return true.
Object Return true.

So just to recap, the falsy values are:

+0, -0

Quick note: in case you like declaring your primitives with their object wrappers, be sure to keep in mind that objects are always truthy, meaning:

let emptyStringObject = new String('')
if(emptyStringObject) {
    console.log(typeof emptyStringObject)
// 'object'

Source: ECMA International