- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
Let’s understand them with examples that relate to real life ?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.
? 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:
AND
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:
OR
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
? 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! ?");
}
| Operator | Result is true if... |
|---|---|
| AND | Both conditions are true |
| OR | At least one condition is true |
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