Truthy & Falsy Values
Truthy & Falsy Values
Section titled “Truthy & Falsy Values”Introduction
Section titled “Introduction”In JavaScript, every value has an inherent boolean “truthiness” — it’s either truthy (evaluates to true in a boolean context) or falsy (evaluates to false).
Why Do We Need This?
Section titled “Why Do We Need This?”Truthy/falsy checks are used everywhere: if statements, logical operators &&/||, and ternary expressions. Understanding them is key to writing clean conditional logic.
Falsy Values
Section titled “Falsy Values”There are exactly 6 falsy values in JavaScript:
false; // the boolean false0; // zero''; // empty stringnull; // nullundefined; // undefinedNaN; // Not a NumberTruthy Values
Section titled “Truthy Values”Everything else is truthy:
true;1; // any non-zero number'hello'; // any non-empty string[]; // empty array{}; // empty objectfunction(){}; // any function'false'; // the string "false" — truthy!Visual Explanation
Section titled “Visual Explanation”flowchart TD Value[Is this value falsy?] Check{"Value === false / 0 / '' / null / undefined / NaN?"} Yes["⬇️ Evaluates to false"] No["⬇️ Evaluates to true"]
Value --> Check Check -->|Yes| Yes Check -->|No| NoPractical Usage
Section titled “Practical Usage”// Default values with ||const name = userInput || 'Guest';// If userInput is falsy (empty, null, undefined), use 'Guest'
// Guard with &&isLoggedIn && renderDashboard();// Only render if isLoggedIn is truthyCommon Mistakes
Section titled “Common Mistakes”// ❌ Wrongif (value == false) { } // Too broad — catches 0 and ''
// ✅ Rightif (value === false) { } // Only actual false
// ❌ Wrong — 0 is falsyif (score) { } // Fails when score is 0
// ✅ Rightif (score !== null && score !== undefined) { }Summary
Section titled “Summary”- Only 6 falsy values:
false,0,'',null,undefined,NaN - Everything else is truthy
- Use
!!to check truthiness:!!value - Be careful with
0— it’s falsy but often a valid value