HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Logical Operators

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.


The Three Main Logical Operators

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)

1. Logical AND (&&)

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)

2. Logical OR (||)

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)

3. Logical NOT (!)

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)
Note: Logical operators are almost always used with if statements and loops to create more complex and powerful decision-making logic.

Short-Circuit Evaluation

JavaScript uses "short-circuiting" for logical operations. This means:

  • In an AND (&&) operation, if the first value is false, JavaScript stops and returns false immediately without checking the second value.
  • In an OR (||) operation, if the first value is true, JavaScript stops and returns true immediately without checking the second value.

Real-World Example

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.");
}
Tip: Always use parentheses when combining different logical operators to make the order of evaluation clear to both JavaScript and other developers who read your code.

Key Points to Remember

  • && requires both sides to be true
  • || requires at least one side to be true
  • ! flips the boolean value (true becomes false)
  • Logical operators help build complex conditions for if statements
  • Short-circuiting saves processing time by stopping as soon as the result is known