In JavaScript, a boolean is a data type that represents a logical value, which can be either true or false. Booleans are commonly used in conditional statements, comparisons, and boolean logic operations. Here's how you can work with booleans in JavaScript:
You can declare boolean variables using the true and false keywords:
let isRaining = true;
let isSunny = false;
Comparison operators return boolean values based on the comparison result:
let x = 5;
let y = 10;
console.log(x < y); // Output: true
console.log(x === y); // Output: false
Booleans are often used in conditional statements to control the flow of code execution:
let isLogged = true;
if (isLogged) {
console.log('User is logged in.');
} else {
console.log('User is not logged in.');
}
JavaScript provides logical operators ( && , || , ! ) for boolean logic operations:
let isMorning = true;
let isWeekend = false;
console.log(isMorning && isWeekend); // Output: false
console.log(isMorning || isWeekend); // Output: true
console.log(!isMorning); // Output: false
You can convert other data types to booleans using the Boolean() function:
console.log(Boolean(0)); // Output: false
console.log(Boolean('')); // Output: false
console.log(Boolean(10)); // Output: true
console.log(Boolean('hello')); // Output: true
These are some common use cases for booleans in JavaScript. They are fundamental for implementing conditional logic and decision-making in your code.