JavaScript Logical Operators
Logical operators in JavaScript are used to combine or negate Boolean values and expressions. They return true
or false
.
1️⃣ Logical Operators in JavaScript
Operator | Name | Example | Description |
---|---|---|---|
&& | Logical AND | a && b | Returns true if both a and b are true . |
` | ` | Logical OR | |
! | Logical NOT | !a | Returns true if a is false , and vice versa. |
2️⃣ Logical AND (&&
)
✅ Returns true
only if both conditions are true
.
🚫 If any condition is false
, it returns false
.
🔹 Use Case: Checking multiple conditions
3️⃣ Logical OR (||
)
✅ Returns true
if at least one condition is true
.
🚫 Returns false
only if both conditions are false
.
🔹 Use Case: Providing default values
4️⃣ Logical NOT (!
)
✅ Negates a Boolean value (true
→ false
, false
→ true
).
🔹 Use Case: Checking if a variable is falsy
5️⃣ Short-Circuiting in Logical Operators
Logical AND (&&
) Short-Circuiting
If the first operand is false
, JavaScript stops evaluating and returns that value.
Logical OR (||
) Short-Circuiting
If the first operand is true
, JavaScript stops evaluating and returns that value.
🔹 Use Case: Setting default values
6️⃣ Combining Logical Operators
You can combine &&
, ||
, and !
in complex conditions.
🎯 Summary
✅ &&
(AND) → Both must be true
✅ ||
(OR) → At least one must be true
✅ !
(NOT) → Reverses the Boolean value
✅ Short-circuiting improves performance
✅ Use OR (||
) for default values
🚀 Now you can handle logical conditions in JavaScript like a pro! Let me know if you need more details. 😊