How to Check if All Array Values Are Equal in JavaScript

JavaScript’s allEqual() function can be used to check whether every value of an array is equal. Here’s how to use it.

Published on Jan. 22, 2025
JavaScript developer reviewing code on computer
Image: Shutterstock / Built In
Brand Studio Logo

JavaScript allEqual() is a function that checks whether every value of your record or array is equal to each other. It returns true if all records of a collection are equal; otherwise, it returns false

JavaScript allEqual() Function Defined

The JavaScript allEqual() function checks whether or not every value of an array is equal to each other. If it is, it returns true. If it isn’t equal, it returns false. Here is the syntax:

const allEqual = arr => arr.every(val => val === arr[0]);

Let’s look at the syntax.

 

JavaScript allEqual() Syntax

const allEqual = arr => arr.every(val => val === arr[0]);

This function will get an array from a parameter, and in return, it’s using every method of the array to get individual records to compare it with the 0th index record. It’ll return true if all records are the same as the 0th index record, otherwise, it’ll return false. Now, let’s look at the results.

A tutorial on how to use JavaScript allEqual(). | Video: TutorialSpot

 

How to Check if All Array Values Are Equal in JavaScript Examples

Result 1: False

const result = allEqual([ 3, 4, 5, 5, 5]) // output: false

Result 2: True

const result = allEqual([ 5, 5, 5, 5, 5]) // output: true

As the first result shows, on the 0th index record (3) won’t match the first index record, and it’ll return false from then on. In the second result, it’ll compare every record with 0th index record (5), where it is equal to all records. So, the output is given as true.

It’s important to note that the function will terminate after the first wrong match, and the result will be returned with a false value.

Frequently Asked Questions

The JavaScript allEqual() function follows this syntax:

const allEqual = arr => arr.every(val => val === arr[0]);

JavaScript’s allEqual() function allows you to check every value of an array and determine if it is equal. It’ll return true if the values are equal and false if they aren’t equal. Here are two sample results from the allEqual() function:

Example 1: True

const result = allEqual([ 5, 5, 5, 5, 5]) // output: true

Example 2: False

const result = allEqual([ 3, 4, 5, 5, 5]) // output: false
Explore Job Matches.