The Boolean Object
True or False
A Boolean represents one of two values: true or false. While we usually use primitive booleans (e.g., let isActive = true), JavaScript technically has a Boolean object that acts as a wrapper.
The Boolean() Function
You can use the Boolean() function to find out if an expression (or a variable) is true or false.
console.log(Boolean(10 > 5)); // true
console.log(Boolean(10 < 5)); // false
Truthy and Falsy Values
In JavaScript, you don't just evaluate true and false. EVERY single value in JavaScript inherently evaluates to true ("truthy") or false ("falsy") when placed in a boolean context (like an if statement).
Falsy Values: There are only 6 falsy values in JavaScript. If you memorize these, everything else is truthy!
false0(Zero)""(Empty string)nullundefinedNaN
let name = ""; // Empty string is falsy
if (name) {
console.log("We have a name!");
} else {
console.log("Name is missing!"); // This runs!
}
Truthy Values: Everything that is not in the falsy list above is truthy.
Boolean("Himanshu"); // true (Non-empty string)
Boolean(42); // true (Non-zero number)
Boolean([]); // true (Empty array is truthy!)
Boolean({}); // true (Empty object is truthy!)
💡 Himanshu's Tip:
When checking if an array has items, never do if (myArray). Because an empty array is "truthy", that statement will always run! Instead, check its length: if (myArray.length > 0).
Interview Questions
- Name at least 4 of the 6 "falsy" values in JavaScript.
- Is an empty array
[]considered truthy or falsy? - What is the difference between
nullandundefinedwhen evaluated in a boolean context?