Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

Multiple conditions – JavaScript

Length: 10 minutes

Details

With a normal if statement, you can only test one condition. However, if you’d like to test 2 or more conditions before executing some code, you can use the logical AND operator and the logical OR operator. You can also use these operators with else if conditions.

Logical AND operator

To test if more than one condition is true, use the logical AND operator (&&). With the AND operator, the block will only run if both conditions are true. The first condition is on the left side of the AND operator and the second is on the right.

if (1 > 0 && 2 > 1) {
  console.log("Both conditions are true");
} 

In the example above, the first block of code will run because both conditions are true.

if (1 > 0 && 2 < 1) {
  console.log("Both conditions are true");
} else {
  console.log("At least one of the conditions is false");
}

In the example above, the else block will run because the second condition is false. As long as one of the conditions is false, the if block will be skipped.

Logical OR operator

To test if at least one condition is true among multiple conditions, use the logical OR operator (||). With the OR operator, the code in the if block will run as long as one of the conditions is true.

if (1 > 0 || 1 > 2) {
  console.log("At least one of the conditions is true");
}

In the example above, the if block will run because the first condition is true (even though the second condition is false).

if (1 < 0 || 1 > 2) {
  console.log("At least one of the conditions is true");
} else {
  console.log("Both conditions are false");
}

In the example above, the else block will run because both conditions are false.

Demo

Exercises

Try the 4 code snippets from the Details section in the console.

Reference

Logical AND on MDN

Logical OR on MDN

Back to: JavaScript Reference > JS Conditional Statements