Logical Operators
Overview
Logical operators are used to combine multiple boolean conditions together, or to invert a boolean condition.
JavaScript provides three core logical operators: Logical AND (&&), Logical OR (||), and Logical NOT (!).
These operators also employ a powerful feature called Short-Circuit Evaluation. As soon as the outcome of the entire expression is determined, JavaScript stops evaluating the rest of the expression. This is frequently used in React for conditional rendering.
Syntax
const hasTicket = true;
const isVip = false;
// AND (&&) - BOTH must be true
console.log(hasTicket && isVip); // false
// OR (||) - AT LEAST ONE must be true
console.log(hasTicket || isVip); // true
// NOT (!) - Inverts the boolean
console.log(!hasTicket); // falseconst isLoggedIn = true;
// If isLoggedIn is false, showDashboard() is NEVER called.
// This is a common pattern in React.
isLoggedIn && showDashboard();
const username = user.name || "Anonymous";
// If user.name is falsy (e.g. empty string), it assigns "Anonymous"Common Pitfalls
- Using
||to provide default values when the intended value might legitimately be0orfalse. For example,const delay = userDelay || 3000;. IfuserDelayis0, it falls back to 3000. Use the Nullish Coalescing Operator (??) instead.
Interview Questions
It means logical expressions are evaluated left to right, and evaluation stops as soon as the outcome is certain. In false && func(), func() is never executed. In true || func(), func() is never executed.
|| (OR) operator and the ?? (Nullish Coalescing) operator?|| returns the right side if the left side is falsy (0, '', false, null, undefined). ?? returns the right side ONLY if the left side is null or undefined. ?? is much safer for assigning defaults.
Real-World Example
Validating a form submission only if all critical fields are filled out.
if (emailInput !== "" && passwordInput !== "" && termsAccepted === true) {
submitForm();
}Check Your Knowledge
Test your understanding of Logical Operators with these quick questions.