JavaScript Logical Operators

Logical operators combine or invert boolean expressions, letting you build the compound conditions that control program flow.

The three logical operators

JavaScript provides three logical operators: AND written as &&, OR written as ||, and NOT written as !. AND requires both sides to be true, OR requires at least one side to be true, and NOT flips a boolean to its opposite. Together they let you express rules like allow access if the user is logged in and has permission.

Combining conditions

<!DOCTYPE html>
<html>
<body>

<h2>Combining conditions</h2>

<script>
let isLoggedIn = true;
let isAdmin = false;

console.log(isLoggedIn && isAdmin); // false  both must be true
console.log(isLoggedIn || isAdmin); // true   at least one is true
console.log(!isAdmin);              // true   NOT flips false to true

let canEdit = isLoggedIn && !isAdmin;
console.log(canEdit);               // true
</script>

</body>
</html>

Truthy, falsy, and short-circuiting

Logical operators do not only work on true and false; they work on any value using the ideas of truthy and falsy. The falsy values are false, 0, empty string, null, undefined, and NaN, and everything else is truthy. The operators also short-circuit: && stops at the first falsy operand and || stops at the first truthy one, returning that operand rather than a plain boolean.

Short-circuit evaluation

<!DOCTYPE html>
<html>
<body>

<h2>Short-circuit evaluation</h2>

<script>
let name = "";
let displayName = name || "Guest"; // empty string is falsy
console.log(displayName);          // "Guest"

let user = { name: "Mia" };
// && returns the last value if the first is truthy
console.log(user && user.name);    // "Mia"

// Handy for running code only when a value exists
let cart = null;
cart && cart.checkout();           // does nothing, no error
</script>

</body>
</html>

The nullish coalescing operator

Closely related is the nullish coalescing operator (??). It returns the right-hand value only when the left side is null or undefined, ignoring other falsy values like 0 or an empty string. This makes it safer than || when a legitimate value could itself be falsy, such as a quantity of zero.

?? versus ||

<!DOCTYPE html>
<html>
<body>

<h2>?? versus ||</h2>

<script>
let quantity = 0;

console.log(quantity || 10); // 10  because 0 is falsy
console.log(quantity ?? 10); // 0   because 0 is not null/undefined

let nickname = null;
console.log(nickname ?? "Anonymous"); // "Anonymous"
</script>

</body>
</html>
OperatorNameReturns true / value when
&&Logical ANDboth operands are truthy
||Logical ORat least one operand is truthy
!Logical NOTthe operand is falsy
??Nullish coalescingleft side is null or undefined
Note: Because && and || return one of their operands rather than a strict boolean, they are widely used to supply default values and to guard against errors before accessing a property.