Truthy falsy

2 snippets in JavaScript

JSJavaScript

Type Coercion

JS · Data Types
Syntax
implicit: value + "" | +value | !!value
explicit: String(v) | Number(v) | Boolean(v)
Example
console.log("5" + 3);    // "53" (string concat)
console.log("5" - 3);    // 2   (numeric)
console.log(+"42");       // 42  (to number)
console.log(!!"hello");   // true (to boolean)
console.log(Number(""));  // 0
console.log(Number("ab")); // NaN

Note The + operator with a string always coerces to string. Prefer explicit conversion (Number(), String()) to avoid surprises.

Falsy Values

JS · Data Types
Syntax
false | 0 | -0 | 0n | "" | null | undefined | NaN
Example
const values = [false, 0, -0, 0n, "", null, undefined, NaN];
const truthyOnes = values.filter(Boolean);
console.log(truthyOnes.length);
Output
0

Note Everything else is truthy, including empty objects {}, empty arrays [], and the string "false". This trips up many developers.

Frequently asked questions

How does JavaScript handle truthy falsy?
JavaScript covers this with 2 copy-ready snippets on this page. The "Type Coercion" snippet in JavaScript uses `implicit: value + "" | +value | !!value`.
Which code does the JavaScript example use?
The "Type Coercion" snippet uses `implicit: value + "" | +value | !!value`, from the Data Types section of the JavaScript cheat sheet.
What other JavaScript snippets are shown for "truthy falsy"?
Besides "Type Coercion", this page also shows "Falsy Values".
Is there anything to watch out for?
Yes. For "Type Coercion": The + operator with a string always coerces to string. Prefer explicit conversion (Number(), String()) to avoid surprises.