Booleans
Booleans represent one of two values: true or false.
Syntax
let isReady = true;
Boolean(value)A Boolean represents truth: it is either true or false. Booleans are the basis of all decisions in code.
Truthy and falsy
Every value is either truthy or falsy when used as a condition. The falsy values are: false, 0, '' (empty string), null, undefined, and NaN. Everything else is truthy.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Toggle a sidebar's visibility state with a boolean flag that flips on button click.
- Short-circuit an API call when a boolean isAuthenticated flag is false.
- Store a checkbox's checked state as a boolean in form state before submitting.
More examples
Boolean flag for UI state
Flips a boolean flag with the NOT operator to track an open/closed UI state.
let isMenuOpen = false;
function toggleMenu() {
isMenuOpen = !isMenuOpen;
console.log("Menu open:", isMenuOpen);
}
toggleMenu(); // true
toggleMenu(); // falseComparison produces a boolean
Shows that a comparison expression evaluates to a boolean value stored in a variable.
const age = 20;
const canVote = age >= 18;
console.log(canVote); // true
console.log(typeof canVote); // "boolean"Truthy and falsy values
Iterates over common values to demonstrate which are truthy and which are falsy in a boolean context.
const values = [0, "", null, undefined, NaN, false, "hello", 1, [], {}];
values.forEach(v => console.log(v, "=>", Boolean(v)));
Discussion