A boolean represents one of two values: true or false. In conditional control flow, JavaScript automatically coerces values to booleans based on whether they are truthy or falsy.
flowchart TD
Eval["JavaScript Value"] --> Check{"Is value in Falsy List?"}
Check -- "Yes" --> Falsy["Evaluates to false (false, 0, -0, 0n, '', null, undefined, NaN)"]
Check -- "No" --> Truthy["Evaluates to true (Everything else: '0', 'false', [], {}, infinity)"]
| Falsy Value | Type | Description |
|---|---|---|
false |
Boolean | Boolean false primitive. |
0 / -0 |
Number | Zero numbers. |
0n |
BigInt | BigInt zero. |
"" |
String | Empty string (length 0). |
null |
Null | Absence of object value. |
undefined |
Undefined | Primitive default for unassigned variables. |
NaN |
Number | Not-a-Number error result. |
// Demonstrating Boolean coercion, double negation (!!), and truthy traps
// 1. Explicit Coercion using Boolean() and !!
const userCount = 0;
const emptyText = "";
const activeList = [];
console.log(`Boolean(0): ${Boolean(userCount)}`); // false
console.log(`!!"": ${!!emptyText}`); // false
console.log(`!![] (Empty Array): ${!!activeList}`); // true! (Objects/Arrays are ALWAYS truthy)
console.log(`!!"0" (String zero): ${!!"0"}`); // true!
// 2. Truthy Check in Guard Condition
function renderHeader(user) {
// If user object is truthy, render welcome message
if (user) {
console.log(`Welcome back, ${user.name}!`);
} else {
console.log("Welcome, Guest!");
}
}
renderHeader({ name: "Maksudur" }); // Welcome back, Maksudur!
renderHeader(null); // Welcome, Guest!
{} and [] evaluate to true in if statements. To check if an array is empty, check arr.length > 0. To check an object, check Object.keys(obj).length > 0.!! for Quick Boolean Casts: !!value is the idiomatic JavaScript shorthand for casting any value to a boolean primitive."false" and "0" are non-empty strings and therefore evaluate to true.What does Boolean(new Boolean(false)) evaluate to, and why?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.