Hello friends π
In this blog, I will explain two simple and powerful tools in JavaScript: the AND (&&) and OR (||) operators. These are called logical operators and are used to check conditions.
Letβs understand them with examples that relate to real life πΆββοΈππ»
π What is AND (&&)
?
The &&
operator checks if both conditions are true β
β
If both are true β result is true
If any one is false β result is false β
π‘ Real-Life Example:
Letβs say you want to go for a walk πΆββοΈ
You will go only if:
β‘οΈ It is not raining βοΈ
AND
β‘οΈ You have free time π
let isNotRaining = true;
let hasFreeTime = true;
if (isNotRaining && hasFreeTime) {
console.log("You can go for a walk! πΆββοΈ");
} else {
console.log("Stay at home! π‘");
}
π If both conditions are true, the walk will happen
π If even one is false, no walk today!
π What is OR (||)
?
The ||
operator checks if at least one condition is true β
If one is true β result is true
If both are false β result is false ββ
π‘ Real-Life Example:
You will order food π if:
β‘οΈ You are hungry π
OR
β‘οΈ There is no food at home π³
let isHungry = false;
let noFoodAtHome = true;
if (isHungry || noFoodAtHome) {
console.log("Order food online! π΅");
} else {
console.log("No need to order food. Eat at home! π½οΈ");
}
π Only one condition needs to be true to order food
π§ Easy to Remember
β‘οΈ &&
β Both conditions must be true β
AND β
β‘οΈ ||
β Only one condition needs to be true β
OR β
π― Quick Real Example
let hasLaptop = true;
let hasInternet = false;
// Check if you can work from home
if (hasLaptop && hasInternet) {
console.log("You can work from home π»π ");
} else {
console.log("You can't work from home π");
}
// Check if you can still do something useful
if (hasLaptop || hasInternet) {
console.log("You can still be productive! π‘");
}
β Summary Table
Operator | Result is true if... |
---|---|
AND | Both conditions are true β β |
OR | At least one condition is true β or β |
I hope this blog helps you understand AND
and OR
operators in a fun and easy way! π
These are very helpful when writing conditions in JavaScript.
Thanks for reading! π»π
~ Himanay Khajuria
Top comments (0)