DEV Community

Cover image for ✨ Understanding `AND (&&)` and `OR (||)` Operators in JavaScript
Himanay Khajuria
Himanay Khajuria

Posted on

✨ Understanding `AND (&&)` and `OR (||)` Operators in JavaScript

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! 🏑");
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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! 🍽️");
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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! πŸ’‘");
}
Enter fullscreen mode Exit fullscreen mode

βœ… 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)