Logical operators in JavaScript allow you to combine multiple conditions and make decisions, just like your brain when deciding whether to hit snooze or get up (spoiler: it's always snooze). Let's dive into the madness!
1. Logical AND (&&
)
This operator returns true
if both conditions are true. Basically, it's like requiring both coffee AND motivation to start coding.
console.log(true && true); // true (Everything is fine!)
console.log(true && false); // false (One thing ruins everything, like a missing semicolon.)
console.log(5 > 3 && 10 < 20); // true (Math still works!)
console.log("JavaScript" === "bad" && 2 + 2 === 5); // false (Nice try!)
2. Logical OR (||
)
Returns true
if at least one condition is true. It's like choosing between pizza or burgers—either way, you're winning.
console.log(true || false); // true (At least one is true!)
console.log(false || false); // false (Nothing to save you now!)
console.log(10 > 5 || 2 > 100); // true (One of them is correct!)
console.log("JavaScript" === "easy" || "Life" === "simple"); // false (Lies everywhere!)
3. Logical NOT (!
)
Flips the boolean value. Think of it as JavaScript saying "Nope!" to whatever you thought was true.
console.log(!true); // false (Opposite Day!)
console.log(!false); // true (Logic!)
console.log(!(10 > 5)); // false (5 is still less than 10, sorry.)
console.log(!"JavaScript" === true); // false (JavaScript exists, whether you like it or not!)
4. Short-Circuit Evaluation
Logical operators don’t always check both conditions. If JavaScript already knows the result, it stops evaluating. Lazy, right?
console.log(true || someFunction()); // true (JavaScript doesn't even bother calling someFunction!)
console.log(false && someFunction()); // false (JavaScript is like, "Why even check?")
5. Fun with Logical Operators
JavaScript sometimes does weird things with logical operators. Here are some mind-bending examples:
console.log("" || "Hello"); // "Hello" (Empty string is falsy!)
console.log(0 || 42); // 42 (0 is falsy, 42 wins!)
console.log(null && "Oops"); // null (First falsy value stops everything!)
console.log(undefined || "Fallback"); // "Fallback" (Undefined is falsy, so fallback it is!)
Conclusion
Logical operators in JavaScript help you make decisions, but they also bring some chaos. Always test your conditions carefully, and remember—when in doubt, just blame JavaScript!
0 Comments