On this page
Boolean and Truthy/Falsy
The boolean type has only two values: true and false. Booleans are essential for control flow — every condition in if, while, and loops ultimately evaluates to a boolean (or a value treated as one).
Boolean Literals
let isActive = true;
let isDeleted = false;
console.log(typeof isActive); // 'boolean'
Comparison Results
Comparison operators always return booleans:
console.log(5 > 3); // true
console.log(5 === '5'); // false
console.log('a' === 'a'); // true
Truthy and Falsy Values
In JavaScript, every value is either truthy or falsy when used in a boolean context.
Falsy values (only 8)
| Value | Example |
|---|---|
false |
if (false) |
0 |
if (0) |
-0 |
|
0n |
BigInt zero |
"" |
Empty string |
null |
|
undefined |
|
NaN |
Truthy values
Everything else is truthy, including:
console.log(Boolean('hello')); // true
console.log(Boolean([])); // true (empty array is truthy!)
console.log(Boolean({})); // true
console.log(Boolean('0')); // true (non-empty string)
console.log(Boolean('false')); // true
Using Truthy/Falsy in Code
let username = '';
// Short-circuit: use default if username is falsy
let displayName = username || 'Guest';
console.log(displayName); // 'Guest'
// Nullish coalescing: only null/undefined trigger default
let count = 0;
console.log(count || 10); // 10 (0 is falsy)
console.log(count ?? 10); // 0 (0 is not nullish)
Converting to Boolean
Boolean(1); // true
Boolean(0); // false
!!'hello'; // true (double negation trick)
!!''; // false
Practical Examples
// Check if array has items
let items = [];
if (items.length) {
console.log('Has items');
} else {
console.log('Empty'); // runs
}
// Guard clause
function greet(name) {
if (!name) {
console.log('Please provide a name');
return;
}
console.log('Hello, ' + name);
}
greet(''); // Please provide a name
greet('Alice'); // Hello, Alice
Boolean in Logical Expressions
// AND returns first falsy or last value
console.log(true && 'yes'); // 'yes'
console.log(false && 'yes'); // false
// OR returns first truthy or last value
console.log(null || 'default'); // 'default'
console.log('hi' || 'default'); // 'hi'
Understanding truthy/falsy behavior helps you write concise conditions and avoid subtle bugs with values like 0 and ''.