Skip to main content

Command Palette

Search for a command to run...

Testing Array Elements in JavaScript

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

Updated
1 min read
Testing Array Elements in JavaScript
A

I have been a full-stack developer for twelve years and am currently part of the Cloud FinOps team at Atlassian. I previously ran an App development agency, managing various teams across design and development, leading web, backend and native mobile app developers in Australia and Europe. My strengths are system architecture design and communicating complicated tech to everyday people. Having helped scale tech at numerous startups, I am passionate about making a positive difference. When not working, you can find me writing tech articles and teaching Javascript and React at SheCodes, an initiative helping to get more women into tech. I regularly give talks on various topics, focusing on the impact the technology we build can have. I am devastated by the state of the world, love a good political rant and can often be swearing at no one in particular. I enjoy building things in JavaScript, Deno and Node.

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.

D

Loose the return statement and make it a oneliner

1
A

100%. I used the return statement here to make it more clear for people who are new to JavaScript.