Truthy and Falsy Values
Truthy and Falsy Values
Section titled βTruthy and Falsy ValuesβWhat it means
Section titled βWhat it meansβAny JavaScript value can be evaluated as true or false in a boolean context (like an if condition), even if it isnβt actually a boolean. Only a specific, fixed set of values are falsy: false, 0, -0, "", null, undefined, and NaN. Every other value β including "0", [], and {} β is truthy.
Examples
Section titled βExamplesβif ("") console.log("truthy"); // doesn't run -- "" is falsyif ("0") console.log("truthy"); // runs -- non-empty string is truthy!if (0) console.log("truthy"); // doesn't run -- 0 is falsyif ([]) console.log("truthy"); // runs -- empty array is truthy!if ({}) console.log("truthy"); // runs -- empty object is truthy!
const name = "";console.log(name || "Guest"); // "Guest" -- falls back because "" is falsyconsole.log(Boolean(name)); // false -- explicit conversion
console.log(!!"hello"); // true -- double-negation converts to booleanconsole.log(!!0); // falseCommon mistake
Section titled βCommon mistakeβAssuming an empty array or object is falsy β both [] and {} are truthy in JavaScript, unlike some other languages, so if (myArray) doesnβt tell you whether the array has items.
const items = [];
if (items) { console.log("has items"); // runs! [] is truthy, regardless of length}
// Correct way to check for an empty arrayif (items.length > 0) { console.log("has items"); // correctly does NOT run}Quick practice
Section titled βQuick practiceβ-
List the seven falsy values in JavaScript.
Answer
false,0,-0,"",null,undefined, andNaN. -
Is an empty array
[]truthy or falsy?Answer
Truthy β arrays and objects are always truthy in JavaScript, even when empty. -
What does
!!valuedo?Answer
Convertsvalueto its explicit boolean equivalent β the first!negates and coerces to boolean, the second!negates it back to the "real" truthy/falsy value.