How to use for…of loop In Javascript

The for…of loop iterates over the iterable objects (like Array, Map, Set, arguments object, …,etc) and will check the element is same as the first element.

Example: This example shows the use of for-of loop for checking the equality of all the element in the given array.

Javascript
const arr = [1, 1, 1, 1];
const arr1 = [1, 1, 2];
function allEqual(array) {
    let areEqual = true;

    for (const element of array) {
        if (element !== array[0]) {
            areEqual = false;
            break;
        }
    }

    return areEqual;
}
console.log(allEqual(arr));
console.log(allEqual(arr1));

Output
true
false

How to check all values of an array are equal or not in JavaScript ?

Ensuring all values in an array are equal is a common task in JavaScript, useful for validating data consistency and simplifying conditional checks. This guide provides an overview of efficient methods to determine if an array contains identical elements.

Below are the approaches used to check if all values of an array are equal or not in JavaScript:

Table of Content

  • 1. Using Array.every() method
  • 2. Using Array.reduce() method
  • 3. Using Set
  • 4. Using for…of loop
  • 5. Using filter() Method

Similar Reads

1. Using Array.every() method

First, get the array of elements.Pass it to an arrow function, which calls every() method on each array element and returns true if each element matches the first element of the array....

2. Using Array.reduce() method

First, get the array of elements.Pass it to a function, which calls reduce() method on the array element.Return true if each element matches the first element of the array....

3. Using Set

In this article, we will pass the array to the Set constructor, and using the size property we can access the length of the array. As we know set stores unique elements and if the size of the set is 1 then it denotes that all the elements in the array are equal....

4. Using for…of loop

The for…of loop iterates over the iterable objects (like Array, Map, Set, arguments object, …,etc) and will check the element is same as the first element....

5. Using filter() Method

In this approach, we will filter all the elements which are equal and compare the length of the new array with the original array....