Logical operators are used to combine multiple boolean conditions and make complex decisions in programs. In JavaScript, logical operators have a powerful feature called short-circuit evaluation that allows them to return actual values rather than just booleans.
1. The Three Core Logical Operators
Operator
Name
Syntax
Description
&&
Logical AND
A && B
Returns true ONLY if both operands are truthy
**`
`**
Logical OR
`A
B`
Returns true if at least one operand is truthy
!
Logical NOT
!A
Inverts the boolean truthiness of operand
2. Truth Tables
Logical AND (&&):
1console.log(true&&true);// true
2console.log(true&&false);// false
3console.log(false&&true);// false
4console.log(false&&false);// false
Logical OR (||):
1console.log(true||true);// true
2console.log(true||false);// true
3console.log(false||true);// true
4console.log(false||false);// false
Logical NOT (!):
1console.log(!true);// false
2console.log(!false);// true
3
4// Double NOT (!!) - Converts ANY value to its strict boolean equivalent:
5console.log(!!"Hello");// true
6console.log(!!0);// false
7console.log(!!null);// false
3. Short-Circuit Evaluation: How JS Actually Evaluates
In JavaScript, && and || do not simply return true or false. They return the value of the actual operand that decided the outcome!
How Logical AND (&&) Short-Circuits:
Evaluates from left to right.
If it encounters a falsy value, it stops immediately and returns that falsy value!
If all values are truthy, it returns the last value.