When we write conditions in JavaScript, we often need to combine multiple conditions or reverse a condition. This is where logical operators like &&
, ||
, and !
come into play. Today, I explored how these operators work and how they can be used effectively.
🔗 1. The and
Operator (&&
)
The &&
operator returns true
only if both conditions are true.
Syntax:
condition1 && condition2
Example:
let age = 25;
if (age > 18 && age < 30) {
console.log("You are in your twenties!");
}
-
Here, both conditions must be true:
-
age > 18
-
age < 30
-
So, the message is logged .
🔗 2. The or
Operator (||
)
The ||
operator returns true
if at least one of the conditions is true.
Syntax:
condition1 || condition2
💡 Example:
let day = "Saturday";
if (day === "Saturday" || day === "Sunday") {
console.log("It's the weekend!");
}
- Either
day === "Saturday"
orday === "Sunday"
is enough to log the message.
🔗 3. The not
Operator (!
)
The !
operator is used to reverse a boolean value.
Syntax:
!condition
Example:
let isRaining = false;
if (!isRaining) {
console.log("You can go for a walk.");
}
- Since
isRaining
isfalse
,!isRaining
becomestrue
, so the message is logged .
Tip to Remember
-
&&
= All must be true -
||
= At least one must be true -
!
= Opposite of the condition
Practice Example
Try this in your browser console:
let isLoggedIn = true;
let isAdmin = false;
if (isLoggedIn && !isAdmin) {
console.log("Welcome, user!");
}
Final Thoughts
Understanding these basic logical operators is essential for writing smart and readable JavaScript code. I enjoyed experimenting with these operators and now feel more confident using them in if
statements and other logical conditions.
Top comments (0)