Logical Operators in JavaScript
🧠 What Are Logical Operators?
Logical operators in JavaScript are used to combine or invert boolean values. These are especially useful in control flow (like if statements) to make decisions based on multiple conditions.
>>“Logic is the silent engine behind decision-making.” 🤖
🔢 Types of Logical Operators
| Operator | Name | Description | Example |
|---|---|---|---|
| && | AND | Returns true if both operands are true | true && false → false |
| || | OR | Returns true if at least one operand is true | false || true → true |
| ! | NOT | Inverts the boolean value | !true → false |
💡 Truthy & Falsy Reminder
Note
JavaScript treats values like 0, "", null, undefined, and NaN as falsy. Everything else is considered truthy.
📊 Examples
Basic Logical Operations
console.log(true && true); // true
console.log(true && false); // false
console.log(false || true); // true
console.log(false || false); // false
console.log(!true); // false
console.log(!false); // true🎯 Real-World Usage
Logical Operators in Conditionals
const isLoggedIn = true;
const hasPermission = false;
if (isLoggedIn && hasPermission) {
console.log("Access granted");
} else {
console.log("Access denied"); // This line runs
}Using OR for Defaults
const userColor = null;
const defaultColor = "blue";
const finalColor = userColor || defaultColor;
console.log(finalColor); // "blue"NOT Operator Example
const isDay = false;
if (!isDay) {
console.log("It's night time"); // Output: It's night time
}🧪 Short-Circuit Evaluation
Logical expressions in JavaScript are evaluated left to right and will short-circuit:
- false && anything → false (skips the second part)
- true || anything → true (skips the second part)
Note
💡 Logical operators don’t always return true or false — they return the actual value of the last evaluated operand.
Short-Circuit Examples
console.log("Hello" && 0); // 0
console.log(null || "Fallback"); // "Fallback"
console.log(!0); // true📚 Further Reading
>>“Where there’s logic, there’s clarity. Write your conditions wisely.” 🧘