Problem Statement
How many falsy values are there in JavaScript?
Explanation
JavaScript has exactly 8 falsy values. Everything else is truthy.
The 8 falsy values:
False, the boolean false.
Zero, the number zero.
Negative zero, which is minus zero.
BigInt zero, which is 0n.
Empty string with no characters.
Null.
Undefined.
NaN, which means Not a Number.
Memory trick: F O Z E N U N, sounds like frozen.
False, zero including 0n and negative 0, Empty string, Null, Undefined, NaN.
Common mistakes:
Empty arrays and empty objects are truthy, not falsy.
The string zero is truthy.
The string false is truthy.
Anything not in the list of 8 is truthy.
Code Solution
SolutionRead Only
// All 8 falsy values
if (false) { } // falsy
if (0) { } // falsy
if (-0) { } // falsy
if (0n) { } // falsy (BigInt zero)
if ('') { } // falsy (empty string)
if (null) { } // falsy
if (undefined) { } // falsy
if (NaN) { } // falsy
// Common truthy values (SURPRISING!)
if ('0') { } // truthy! (string with zero)
if ('false') { } // truthy! (string false)
if ([]) { } // truthy! (empty array)
if ({}) { } // truthy! (empty object)
if (function(){}) { } // truthy! (functions)
// Practical usage
let name = '';
if (name) {
console.log('Has name');
} else {
console.log('No name'); // This runs (empty string is falsy)
}
// Convert to boolean
console.log(Boolean(0)); // false
console.log(Boolean('hello')); // true
console.log(Boolean([])); // true
// Double NOT operator
console.log(!!0); // false
console.log(!!'hello'); // true
console.log(!![]); // true