Testing Array Elements in JavaScript

Testing Array Elements in JavaScript

Using Array.prototype.every() to validate arrays in JavaScript

There are so many functions in JavaScript, especially in arrays, that it can be hard to keep track of all of them. You may not have used every before, but it is a simple way to ensure each element in the array passes a test.

The array method returns a truthy value if each element passes the check inside the provided function or a falsy value if one or more fail.

const users = [
  {id: 1, name: "Alexander", created: 2015},
  {id: 2, name: "Orhan", created: 2023},
  {id: 3, name: "Akshaya", created: 2023}

const startedBefore2024 = users.every(user => {
  return user.created < 2024
console.log(startedBefore2024) // true
const students = [
    { name: 'Alice', age: 21, hasPassed: true },
    { name: 'Bob', age: 19, hasPassed: false },
    { name: 'Charlie', age: 20, hasPassed: true },
    { name: 'Emily', age: 22, hasPassed: false }

const allStudentsPassed = students.every(student => {
    return student.hasPassed === true;
console.log(allStudentsPassed);  // false

As you can see every is super simple to use and saves you from having to use a custom filter, reduce or for loop. There is support in every major browser for every so start using it today. You can find the full browser breakdown here.