4) Conditionals, Loops and Functions Lesson

The Logical "and" Operator and Logical "or" Operator in JavaScript

3 min to complete · By Ian Currie

Sometimes, you will want your conditional to satisfy more than one condition, or at least one condition out of two or more.

How to Evaluate Multiple Statements

You can achieve this by using logical operators. Let's learn about the and operator - && and the or operator - ||. Have a look at the difference between the two.

The Logical And Operator

The and operator evaluates multiple statements, and only returns true if all statements evaluate to true.

if (age >= 12 && age <= 20) {
  console.log("You're a Teenager!");
}

In the example above, the string "You're a Teenager!" will only be displayed if the age is somewhere between 12 and 20. Both conditions need to be met in order for the conditional to evaluate as true.

The Logical Or Operator

The or operator returns true if any of the conditions evaluate to true.

if (age > 20 || age < 13) {
  console.log("You're not a Teenager!");
}

In the code above, the string "You're not a Teenager!", will be executed if the age is greater than twenty or the age is smaller than 13. In the case of an or operator, both conditions do not need to evaluate as true for the code to be executed.

Illustration of a lighthouse

Remember to always wrap your conditional statements after the if or else if keyword in parentheses, you will get an error if you don't!

How To Use Both Operators in the Same Conditional

The and operator and the or operator can be used in the same conditional statement. Try to understand the code below:

if ((age >= 5 && age < 18) || age > 65) {
  console.log("You are eligible for a discount!");
}
Illustration of a lighthouse

This statement checks if the age value is between 5 and 17, or the age value is over 65.

Summary: The Logical And Operator and Logical Or Operator

  • Logical operators allow you to evaluate multiple conditions in a conditional
  • The logical and only returns true if both statements evaluate to true
  • The logical or returns true if either of the conditions evaluate to true
  • You can use both operators in the same conditional statement