Check if Three Values are Equal in JavaScript

avatar

Borislav Hadzhiev

Fri Nov 05 20212 min read

banner

Photo by Sunny Ng

Check if Three Values are Equal in JavaScript #

Use the logical AND (&&) operator to check if three values are equal, e.g. if (val1 === val2 && val1 === val3). For the if block to run, both conditions have to be satisfied, that is, value1 has to be equal to value2 and value3, which means the 3 values are equal.

index.js
const val1 = 'apple'; const val2 = 'apple'; const val3 = 'apple'; if (val1 === val2 && val1 === val3) { console.log('โœ… The 3 values are equal'); } else { console.log('โ›”๏ธ The values are NOT equal'); }

We used the logical AND (&&) operator to chain multiple conditions.

The if block only runs if these two conditions are met:

  • val1 is equal to val2
  • val1 is equal to val3

If both conditions are met, we know that the three values are equal.

The && operator is evaluated left to right. If the first condition in our if statement returns false, the operator short-circuits and doesn't evaluate the second condition.

For example, in the following if statement, the 10 > 1 condition is never evaluated.

index.js
if (1 > 50 && 10 > 1) { }

We first check if 1 > 50 and get a value of false, so the && operator short-circuits.

Here are some more examples of using the && (and) operator.

index.js
console.log(true && true); // ๐Ÿ‘‰๏ธ true console.log(true && false); // ๐Ÿ‘‰๏ธ false console.log(false && true); // ๐Ÿ‘‰๏ธ false console.log('one' && 'two'); // ๐Ÿ‘‰๏ธ 'two' console.log('one' && ''); // ๐Ÿ‘‰๏ธ '' console.log('' && 'one'); // ๐Ÿ‘‰๏ธ ''

The && operator returns the value of one of the operands.

If the first value we pass to it is a falsy value, it returns the first value, otherwise it returns the second.

Falsy values in JavaScript are: undefined, null, NaN, empty string, false and 0.

An alternative approach is to pass the values to the Set() constructor.

Set objects only store unique values, so any duplicates passed to the constructor get automatically removed.

index.js
const set1 = new Set(['a', 'a', 'a']); console.log(set1); // ๐Ÿ‘‰๏ธ {'a'}

This means that we can pass the values to the Set constructor and if the size of the Set is equal to 1, then all of the passed in values were equal.

index.js
const val1 = 'apple'; const val2 = 'apple'; const val3 = 'apple'; if (new Set([val1, val2, val3]).size === 1) { console.log('โœ… The 3 values are equal'); } else { console.log('โ›”๏ธ The values are NOT equal'); }

Because the Set object does not contain duplicate values, all of the duplicates got removed when initializing the new Set.

If the new Set contains a single element, we can conclude that all of the passed in values were equal.

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