Skip to content

Truthy & Falsey values

Wherever JavaScript expects a boolean, such as in an if, a loop condition, the ! operator or the && and || operators, it accepts a value of any type and converts it. A value that converts to false is called falsy (also spelt falsey), and a value that converts to true is called truthy.

The list of falsy values is short and fixed:

  • false
  • 0, -0 and 0n (the BigInt zero)
  • '', the empty string
  • null
  • undefined
  • NaN

Boolean() performs the same conversion that a condition does, so it can show the result directly:

const values = [false, 0, -0, 0n, '', null, undefined, NaN];
console.log(values.map(Boolean));

This prints:

[
false, false,
false, false,
false, false,
false, false
]

Browsers also treat the legacy object document.all as falsy, for compatibility with very old pages, but it is the only exception of its kind.

Every value not in that list is truthy, including some that look empty or false:

const values = ['0', 'false', ' ', [], {}, -1, Infinity, () => {}];
console.log(values.map(Boolean));

This prints:

[
true, true, true,
true, true, true,
true, true
]

The strings '0' and 'false' are truthy because they are not empty, and so is a string holding only a space. Every object is truthy, including an empty array and an empty object.

Truthiness makes some checks short. Passing Boolean to filter() keeps only the truthy items of an array, which removes empty strings, null and undefined in one step:

const responses = ['Yes', '', 'No', null, 'Maybe', undefined];
const answered = responses.filter(Boolean);
console.log(answered);

This prints:

[ 'Yes', 'No', 'Maybe' ]

To turn a value into a boolean explicitly, use Boolean(value) or !!value. Unary & Double Bang !! Casting covers the second form.

An empty array is truthy, so testing the array itself does not tell you whether it has items. Test its length instead:

const cart = [];
if (cart) {
console.log('An empty array is truthy');
}
if (cart.length === 0) {
console.log('The cart is empty');
}

This prints:

An empty array is truthy
The cart is empty

The other common trap is a default value set with ||. The || operator replaces every falsy value, so a real 0 or an empty string is thrown away along with null and undefined. The nullish coalescing operator ?? replaces only null and undefined, which is usually what a default needs:

const order = { quantity: 0, note: '' };
console.log(order.quantity || 1);
console.log(order.quantity ?? 1);
console.log(order.note || 'No note');
console.log(order.note ?? 'No note');

This prints:

1
0
No note

The last line is the empty string, kept by ?? because it is not null or undefined. Nullish Coalescing Operator and Logical Short Circuiting cover both operators.

Steve Griffith covers this topic in his video Truthy & Falsy Values in JavaScript.