In JavaScript, a Boolean represents one of two values: true or false. Booleans are used heavily in conditions, comparisons, and decision-making structures like if, while, and the ternary operator.
You’ll most often see Booleans as the result of comparing values, or as flags that describe a state (for example, isOnline, isAdmin, hasPermission, etc.).
true and false.10 > 5 produce Boolean values.true or false.if, else, loops, and ternary operators.A Boolean variable is typically created using let, const, or var and assigning it either true or false:
let isOnline = true;
let hasPermission = false;
Most Booleans you work with come from expressions such as comparisons:
console.log(10 > 5); // true
console.log(3 === 4); // false
console.log("a" !== "b"); // true
In JavaScript, values are automatically converted to Booleans in contexts like if conditions. These values are classified as truthy or falsy.
false, 0, "" (empty string), null, undefined, NaN.[] and {}).
if ("Hello") {
console.log("This is truthy!");
}
if (0) {
console.log("This won't run."); // 0 is falsy
}
The built-in Boolean() function converts any value to its Boolean equivalent:
console.log(Boolean(0)); // false
console.log(Boolean("hello")); // true
console.log(Boolean("")); // false
console.log(Boolean([])); // true
This is handy when you want an explicit true or false rather than relying on JavaScript's automatic coercion.
Booleans are at the heart of decision-making structures. For example, checking if a user is old enough to vote:
let age = 20;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("Too young.");
}
The condition age >= 18 evaluates to true or false, which then controls which block of code runs.
Based on the examples above:
console.log(10 > 5); prints true because 10 is greater than 5.console.log(3 === 4); prints false because 3 is not strictly equal to 4.if ("Hello") { ... } runs its block because non-empty strings are truthy.if (0) { ... } does not run because 0 is falsy.Boolean("hello") returns true, while Boolean("") returns false.Understanding these outputs helps you predict how your code will behave in different conditions.
Boolean() when you want an explicit conversion instead of relying on implicit coercion.false, 0, "", null, undefined, NaN.[] and objects {} are truthy, even though they are “empty”.=== and !==) to avoid unexpected type coercion.isLoggedIn, hasPermission, or isAdmin.null, [], and {} using Boolean().isLoggedIn and write an if/else block that prints a welcome message only if it is true.age >= 18 in a Boolean variable.if/else statement to decide what message to print.score >= 50 or username === "admin".