How to Check if All Values in an Array are Equal in Javascript

In this tutorial, you will learn how to check if all values in an array are equal in javascript. In an array, we can store as many items as we want.  Those items can be of similar type or different types.
  • We have selected two elements button and h1 using the document.querySelector() method and stored them in btnCheck and result variables respectively.
  • We have a global variable users. users holds an array of strings.
  • We have attached the click event listener to the button element.
  • every() method takes an anonymous function as a parameter and returns a Boolean value. As you know, arrays have a 0-based index.  This anonymous function will run for each item and simply check if each item is equivalent to the first item in the array.
  • We are setting the inner text of the h1 element to the Boolean value returned by the every() method.
let btnCheck = document.querySelector('button');
let result = document.querySelector('h1');

let users = ['Peter', 'Peter'];

btnCheck.addEventListener('click', () => {
    let isEqual = users.every(user => user == users[0]);

    result.innerText = isEqual ? 'True' : 'False';
});