A boolean has only two possible values: true and false. Every decision in a program ends up as one of them.
const isLoggedIn = true;
const hasDiscount = false;
console.log(isLoggedIn); // → true
console.log(5 > 3); // → true
console.log(5 === 6); // → false
Comparisons such as >, < and === produce booleans. You will use them in if statements, loops and filters.
Naming booleans
Name them so they read like a question: isOpen, hasItems, canSubmit. Then conditions read like English:
const cart = ["book", "pen"];
const hasItems = cart.length > 0;
if (hasItems) {
console.log("Show the checkout button");
}
Converting to boolean
Any value can be turned into a boolean with Boolean() or with a double not !!.
console.log(Boolean("hello")); // → true
console.log(Boolean("")); // → false
console.log(Boolean(0)); // → false
console.log(Boolean(42)); // → true
console.log(!!"text"); // → true
JavaScript uses this conversion automatically in conditions. The values that become false are called falsy and the rest are truthy. See Truthy and Falsy for the full list.
A common mistake with the strings “true” and “false”
console.log(Boolean("false")); // → true
Any non-empty string is truthy, including the text "false". When you read a value from a form or storage, it is a string. Compare it with === "true" instead of converting it directly.