In JavaScript, logical operators are used to perform logical operations on values, typically used in conditions that evaluate to either true or false (Boolean values). These operators can work with both Boolean values directly or with values of other types, in which case they are converted to Boolean implicitly (truthy or falsy values). Here are the main logical operators in JavaScript:
1. Logical AND (&&)
- Returns
trueif both operands are true; otherwise, returnsfalse. - If the first operand is falsy, it returns the first operand. If the first operand is truthy, it returns the second operand.
console.log(true && true); // true console.log(true && false); // false console.log('Hello' && 123); // 123
2. Logical OR (||)
- Returns
trueif at least one of the operands is true; otherwise, returnsfalse. - If the first operand is truthy, it returns the first operand. If the first operand is falsy, it returns the second operand.
console.log(false || true); // true console.log(false || false); // false console.log('' || 'fallback'); // 'fallback'
3. Logical NOT (!)
- Returns
falseif its single operand can be converted totrue; otherwise, returnstrue. - It effectively inverts the Boolean value of the operand.
console.log(!true); // false console.log(!0); // true
Truthy and Falsy Values
In the context of logical operations, JavaScript values can be categorized as either "truthy" or "falsy". A falsy value is a value that translates to false when evaluated in a Boolean context. JavaScript defines the following falsy values:
false0and-0""(empty string)nullundefinedNaN
All other values are considered truthy, meaning they evaluate to true in Boolean contexts.
Short-Circuit Evaluation
Logical operators in JavaScript use "short-circuit" evaluation to decide the result as soon as possible.
- For
&&(Logical AND): JavaScript evaluates the second operand only if the first operand is truthy. - For
||(Logical OR): JavaScript evaluates the second operand only if the first operand is falsy.
This behavior is useful for writing more concise and efficient code, such as setting default values or conditional execution:
let a;
let b = null;
let c = "Hello";
let result = a || b || c; // "Hello"
In the example above, result is assigned the value "Hello" because it's the first truthy value from left to right.