Specify multiple conditions in an if statement in JS

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

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'); }

In this example 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 executed.

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 execute.

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, in this example, we use 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 parenthesis) is evaluated and returns false.

Then the logical OR (||) operator evaluates the condition to the right. The condition to the right returns true and the if block runs.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee