Logical Operators
Logical Operators
Section titled “Logical Operators”Introduction
Section titled “Introduction”Logical operators work with boolean values and use short-circuit evaluation. They are essential for conditionally executing code.
Visual Explanation
Section titled “Visual Explanation”flowchart TD AND["true && false"] --> ANDR["false"] OR["true || false"] --> ORR["true"] NOT["!true"] --> NOTR["false"]AND (&&)
Section titled “AND (&&)”Returns the first falsy value or the last truthy value:
true && true; // truetrue && false; // false0 && 'hello'; // 0
// Short-circuit — if first is falsy, second is NOT evaluatedfalse && console.log('never runs');OR (||)
Section titled “OR (||)”Returns the first truthy value or the last falsy value:
true || false; // truefalse || 'hello'; // 'hello'0 || null; // null
// Short-circuit — if first is truthy, second is NOT evaluatedtrue || console.log('never runs');NOT (!)
Section titled “NOT (!)”!true; // false!false; // true!0; // true — 0 is falsy!'hello'; // false — 'hello' is truthy!!'hello'; // true — double NOT converts to booleanCommon Patterns
Section titled “Common Patterns”// Default values (with ||)const name = userInput || 'Guest';
// Guard (with &&)isLoggedIn && renderDashboard();
// ToggleisActive = !isActive;Best Practices
Section titled “Best Practices”- Use
||for defaults (but beware of falsy values like0or'') - Use
??(nullish coalescing) when onlynull/undefinedshould trigger defaults - Use
&&for conditional execution
Summary
Section titled “Summary”&&returns first falsy or last truthy||returns first truthy or last falsy!inverts boolean value- Both
&&and||short-circuit