Logical operators are used to determine the logic between variables or values. They are essential for making decisions in your code when you need to check multiple conditions at the same time.
JavaScript provides three primary logical operators:
| Operator | Description | Example |
|---|---|---|
&& |
Logical AND | (x < 10 && y > 1) |
|| |
Logical OR | (x == 5 || y == 5) |
! |
Logical NOT | !(x == y) |
The && operator returns true only if
both statements are true. If even one of them is false, the whole result
is false.
let x = 6;
let y = 3;
console.log(x < 10 && y > 1); // true
console.log(x < 5 && y > 1); // false (because x < 5 is false)
The || operator returns true if at least one
of the statements is true. It only returns false if both statements are false.
let x = 6;
let y = 3;
console.log(x == 5 || y == 5); // false (both are false)
console.log(x == 6 || y == 5); // true (the first one is true)
The ! operator reverses the boolean result. It turns true
into false, and false into true.
let x = 6;
let y = 3;
console.log(!(x == y)); // true (because x == y is false, and ! reverses it)
if
statements and loops to create more complex and powerful decision-making logic.
JavaScript uses "short-circuiting" for logical operations. This means:
Imagine a website that only allows a user to enter a specific area if they are an adult AND they have a ticket:
let age = 20;
let hasTicket = true;
if (age >= 18 && hasTicket) {
console.log("Welcome to the event!");
} else {
console.log("Access denied.");
}
&& requires both sides to be true|| requires at least one side to be true! flips the boolean value (true becomes false)if statements