Spex3
    

JavaScript Logical Operators 🤔


    

    

JavaScript Logical Operators 🤔
Logical operators combine multiple conditions and return a Boolean value (true or false).

1️⃣ List of Logical Operators
Operator Symbol Example Description
AND && true && false → false Returns true only if both conditions are true.
OR ` `
NOT ! !true → false Reverses the Boolean value.

2️⃣ Explanation and Examples

✅ 1. Logical AND (&&)
Returns true only if both conditions are true.


console.log(true && true); // true
console.log(true && false); // false
console.log(5 > 3 && 10 < 20); // true (both conditions are true)
console.log(5 > 10 && 10 < 20); // false (first condition is false)

📌 Use Case: Checking multiple conditions


let age = 25;
let hasID = true;

if (age >= 18 && hasID) {
console.log("You can enter the club.");
} else {
console.log("Access denied.");
}
// Output: "You can enter the club."


✅ 2. Logical OR (||)
Returns true if at least one condition is true.


console.log(true || false); // true
console.log(false || false); // false
console.log(5 > 10 || 10 < 20); // true (second condition is true)
console.log(5 > 10 || 3 > 10); // false (both are false)


📌 Use Case: Providing a default value


let username = "";
let displayName = username || "Guest";
console.log(displayName); // "Guest"


📌 Explanation: If username is empty (""), || assigns "Guest" as the default value.

✅ 3. Logical NOT (!)
Reverses the Boolean value.


console.log(!true); // false
console.log(!false); // true
console.log(!(5 > 3)); // false (since `5 > 3` is `true`)


📌 Use Case: Checking if a value is not present


let isLoggedIn = false;
if (!isLoggedIn) {
console.log("Please log in.");
}

// Output: "Please log in."


3️⃣ Short-Circuit Evaluation 🛑
Logical operators in JavaScript use short-circuiting, meaning they stop evaluating once the result is known.

🔹 AND (&&) Short-Circuiting
If the first condition is false, JavaScript skips the second condition.


console.log(false && console.log("Won't run")); // false


📌 Why? Since false && anything is always false, JavaScript doesn't execute console.log().

🔹 OR (||) Short-Circuiting
If the first condition is true, JavaScript skips the second condition.


console.log(true || console.log("Won't run")); // true


📌 Why? Since true || anything is always true, JavaScript doesn't check console.log().

4️⃣ Summary: Best Practices
✅ Use && when both conditions must be true.
✅ Use || when at least one condition must be true.
✅ Use ! to reverse Boolean values.
✅ Use short-circuiting for efficient code execution.


    Date: 2025-03-29 00:00:00.000000