JavaScript : Booleans

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:

1. Declaring Booleans:


You can declare boolean variables using the true and false keywords:


let isRaining = true;
let isSunny = false;

 

2. Comparison Operators:


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

 

3. Conditional Statements:


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.');
}

 

4. Boolean Logic Operations:


JavaScript provides logical operators ( && , || , ! ) for boolean logic operations:

  • && (Logical AND): Returns true if both operands are true.
  • || (Logical OR): Returns true if at least one of the operands is true.
  • ! (Logical NOT): Returns the opposite boolean value of the operand.


let isMorning = true;
let isWeekend = false;

console.log(isMorning && isWeekend);  // Output: false
console.log(isMorning || isWeekend);  // Output: true
console.log(!isMorning);  // Output: false

 

5. Boolean Conversion:


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.