JS Booleans

Overview

Booleans in JavaScript represent a data type that can have one of two values: true or false. They are fundamental for making decisions and controlling the flow of execution in programs. Booleans play a crucial role in conditional statements, loops, and logical operations.


Creating Booleans

Booleans can be created directly by assigning the values true or false to variables:

Try yourself
        
            let isTrue = true;
let isFalse = false;
        
    

Comparison Operators

Comparison operators return Boolean values based on the comparison of two values. These operators include:

Try yourself
        
            let x = 5;
let y = 10;
let isEqual = x == y;         // false
let isNotEqual = x != y;      // true
let isStrictEqual = x === y;  // false
let isStrictNotEqual = x !== y; // true
let isGreater = x > y;        // false
let isLess = x < y;           // true
let isGreaterOrEqual = x >= y; // false
let isLessOrEqual = x <= y;   // true
        
    

Logical Operators

Logical operators perform logical operations on Boolean values and return a Boolean result. These operators include:

Try yourself
        
            let isTrue = true;
let isFalse = false;
let resultAnd = isTrue && isFalse;  // false
let resultOr = isTrue || isFalse;   // true
let resultNot = !isTrue;            // false
        
    

Conditional Statements

Conditional statements, like if, else if, and else, rely on Booleans to determine which block of code to execute.

Try yourself
        
            let condition = true;

if (condition) {
    console.log('Condition is true.');
} else {
    console.log('Condition is false.');
}
        
    

Loops

Loops use Boolean conditions to determine if they should continue iterating.

Try yourself
        
            let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}
        
    

Functions and Return Values

Functions can return Boolean values, which can then be used in other parts of your program.

Try yourself
        
            function isEven(number) {
    return number % 2 === 0;
}

var result = isEven(4);  // true
        
    

Summary

Booleans in JavaScript are crucial for making decisions and controlling the flow of execution in programs. They are used extensively in conditional statements, loops, and logical operations. Understanding how to work with Booleans is fundamental for writing effective JavaScript code.