How to compare 3 Values in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

Compare 3 Values in JavaScript #

To compare 3 values, use the logical AND (&&) operator to chain multiple conditions. When using the logical AND (&&) operator, all conditions have to return a truthy value for the if block to run.

index.js
const value1 = 10; const value2 = 10; const value3 = 10; if (value1 === value2 && value2 === value3) { // ๐Ÿ‘‡๏ธ this runs console.log('โœ… all 3 values are equal'); } else { console.log('โ›”๏ธ values are NOT equal'); }

In the code example, we used the logical AND (&&) operator to chain two conditions.

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.

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

This means that if the conditions on both sides of the logical AND (&&) operator evaluate to a value other than the aforementioned 6, the if block is ran.

If our example we check if 3 values are equal. Since the conditions on both sides of the operator return true, the if block is executed.

First the condition on the left of the && is evaluated, if it returns a falsy value, the condition on the right hand side is not evaluated at all and the else block is ran.

Let's look at another example.

index.js
const value1 = 10; const value2 = 10; const value3 = 20; if (value1 === value3 && value2 < value3) { console.log('โœ… both conditions are true'); } else { // ๐Ÿ‘‡๏ธ this runs console.log('โ›”๏ธ at least 1 condition is false'); }

In this example, the condition on the left hand side is evaluated.

It checks if 10 === 20, which returns false. The AND (&&) operator short-circuits and returns false, and the else block is executed.

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