Check If Three Values are Equal in JavaScript

Hero image for Check If Three Values are Equal in JavaScript. Image by Markus Spiske.
Hero image for 'Check If Three Values are Equal in JavaScript.' Image by Markus Spiske.

Equality Operators

In JavaScript, we can compare three variables to check if they are equal using the equality operator (==) or the strict equality operator (===). I've discussed the differences between the two in more detail before but as a quick recap: the equality operator compares values after type coercion, whilst the strict equality operator compares both value and type.

For example, let's say we have three variables a, b, and c and we want to check if they are equal:

let a = 1;let b = '1';let c = 1;if (a == b && b == c) {  console.log('a, b, and c are equal');} else {  console.log('a, b, and c are not equal');}//=> 'a, b, and c are equal'

In this example, a and c are both numbers, whilst b is a string. The equality operator will compare the values of a and b after converting the string '1' to a number, so the comparison will return true and the output will be "a, b, and c are equal".

If we want to compare the variables using the strict equality operator instead, it would look like this:

let a = 1;let b = '1';let c = 1;if (a === b && b === c) {  console.log('a, b, and c are equal');} else {  console.log('a, b, and c are not equal');}//=> 'a, b, and c are not equal'

In this case, the comparison will return false because a and b have different types, so the output will be "a, b, and c are not equal".


Using a Ternary

We could also combine our equality operators with a ternary operator:

let a = 1;let b = '1';let c = 1;console.log(  a === b && b === c ? 'a, b, and c are equal' : 'a, b, and c are not equal');//=> 'a, b, and c are not equal'

In this example, the ternary operator checks if a is equal to b and b is equal to c using the strict equality operator; much as we did above. If the comparison returns true, the output will be "a, b, and c are equal" (the lefthand side), otherwise, the output will be "a, b, and c are not equal" (the righthand side).


Using Array.prototype.every

A final option that I've used a few times and is very useful if you've got a lot of values to compare is the Array.prototype.every method, which we can use to check if all elements in an array are equal:

let a = 1;let b = '1';let c = 1;let arr = [a, b, c];console.log(arr.every((val) => val === a));//=> false

In this example, we use the Array.prototype.every method to check if each element in the array is equal to the first (a). Again using the strict equality operator means that we will get back false on this one due to the type mismatch between the variables.


The Wrap‑Up

Comparing two values in JavaScript has always been easy, but comparing three (or more) needn't be any more challenging.


Categories:

  1. Front‑End Development
  2. JavaScript