Specify multiple conditions in an if statement in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Specify multiple conditions in an if statement #

You can use the logical AND (&&) and logical OR (||) operators to specify multiple conditions in an if statement. When using logical AND (&&), all conditions have to be met for the if block to run.

When using logical OR (||), at least one condition has to be met for the if block to run.

index.js
if (5 > 10 || 2 > 10 || 10 > 5) { // 👇️ if block runs console.log('✅ at least one condition is met'); } else { console.log('⛔️ neither condition is met'); }

We used the logical OR (||) operator to chain multiple conditions in an if statement.

If at least one of the conditions returns true, the if block will run.

If none of the conditions return true, the else block will run.

The logical OR (||) operator returns the value to the left if it's truthy, otherwise it returns the value to the right.

Truthy are all values that are not falsy.

The falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number).

Since our comparison operations evaluate to either true or false, if at least one comparison evaluates to true, the if block is run.

Here's an example of specifying multiple conditions using the logical AND (&&) operator.

index.js
if (10 > 5 && 5 > 3) { // 👇️ if block runs console.log('✅ all conditions are met'); } else { console.log('⛔️ not all conditions are met'); }
When using the logical AND (&&) operator in an if statement, all conditions have to be met for the if block to run.

The logical AND (&&) operator returns the value to the left if it's falsy, otherwise it returns the value to the right.

In the example, both of the comparisons return true, therefore the if block runs.

You can also mix and match conditions. Here is an example that uses both operators.

index.js
if ((10 > 20 && 10 > 30) || (10 > 5 && 10 > 3)) { // 👇️ if block runs console.log('✅ at least one condition is met'); } else { console.log('⛔️ neither condition is met'); }

First, the condition to the left (in the parentheses) is evaluated and returns false.

Then the logical OR (||) operator evaluates the condition to the right. The condition to the right returns true, so the if block is run.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.