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.