DEV Community

Tamilselvan K
Tamilselvan K

Posted on • Edited on

Day-24 Understanding and, or, and not Operators in JavaScript

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
Enter fullscreen mode Exit fullscreen mode

Example:

let age = 25;
if (age > 18 && age < 30) {
  console.log("You are in your twenties!");
}
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

💡 Example:

let day = "Saturday";
if (day === "Saturday" || day === "Sunday") {
  console.log("It's the weekend!");
}
Enter fullscreen mode Exit fullscreen mode
  • Either day === "Saturday" or day === "Sunday" is enough to log the message.

🔗 3. The not Operator (!)

The ! operator is used to reverse a boolean value.

Syntax:

!condition
Enter fullscreen mode Exit fullscreen mode

Example:

let isRaining = false;
if (!isRaining) {
  console.log("You can go for a walk.");
}
Enter fullscreen mode Exit fullscreen mode
  • Since isRaining is false, !isRaining becomes true, 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!");
}
Enter fullscreen mode Exit fullscreen mode

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)