JavaScript
This page gently explains how &&, ||, and ! combine conditions and work with truthy and falsy values.
Goal: combine conditions clearly and understand the basic short-circuit behavior of JavaScript logical operators.
Logical operators
Logical operators are useful when an if statement needs more than one condition. They also return values, not only the Boolean words true and false.
&&: both conditions
For a condition, left && right is truthy only when both sides are truthy.
JavaScript
const age = 20;
const hasTicket = true;
if (age >= 18 && hasTicket) {
console.log("You may enter.");
}JavaScript evaluates the left side first. If it is falsy, the right side is not evaluated. This is called short-circuit evaluation.
||: either condition
For a condition, left || right is truthy when at least one side is truthy. If the left side is truthy, JavaScript returns it without evaluating the right side; otherwise it returns the right side.
JavaScript
const displayName = userName || "Guest";This fallback pattern treats an empty string as missing. If an empty string is a valid value and only null or undefined should trigger the fallback, consider the nullish coalescing operator ?? instead.
!: reverse a Boolean result
The unary ! operator converts its operand to a Boolean and reverses it. For example, !true is false. Use parentheses when reversing a combined expression: !(isReady && hasPermission).
Use parentheses for clarity
Operator precedence can make a condition difficult to read. Parentheses show the intended grouping and reduce mistakes.
&&: require all listed conditions.||: accept one of several alternatives.!: express the opposite condition.- Keep side effects out of the right side of a short-circuit expression when possible; whether they run depends on the left side.