Write Cleaner JavaScript Code With .some() And .every() Array Methods

Marc Backes - Feb 3 '20 - - Dev Community

Writing clean and readable code is important. Especially, but not only when working with others. In this article, I'll teach you how to use the lesser known array methods .some() and .every() to write nice, readable code in your next project.

How do they work?

Both functions work in a similar way. What they do is, they iterate over every item of an array and check if a function (defined by the developer) returns true in some or in every item.

Great use cases for this are situations where you need to check if something is true (or false) for a given array.

Examples

Let's assume the following array:

const people = [
    { name: 'John', age: 47 },
    { name: 'Martha', age: 89 },
    { name: 'Edward', age: 31 },
    { name: 'Michele', age: 18 }
];
Enter fullscreen mode Exit fullscreen mode

Every

If we wanted to find out if all of the people in the array are above legal age (>= 18 years), we could write the following code with forEach:

let allAboveAge = true // assume they all are above age
people.forEach(person => { // iterate over every item
    if(person.age < 18) { // check if below age
        allAboveAge = false // at least one is not above age
    }
})
Enter fullscreen mode Exit fullscreen mode

The code above could be hard to understand at first, because it's not easily readable for another developer. They first have to get behind the logic of what you're trying to do.

To achieve the same thing with .every(), you can do it in one easy-to-read line of code:

const allAboveAge = people.every(person => person.age >= 18)
Enter fullscreen mode Exit fullscreen mode

The function you pass to the .every()-method is should give as a result the thing that needs to be true for each and every item in the array. (In this example, person is the item being iterated at a given moment)

Some

.some() works very similar to .every(). The only difference is, that instead of checking that for every item the statement is true, it only checks if for some (at least one!) items it's true.

So, if you were to check if the array contains at least one person that is above age, you can do it with the following statement, using the .some() method:

const oneOrMoreAboveAge = people.some(person => person.age >= 18)
Enter fullscreen mode Exit fullscreen mode

Summary

As you can see, both methods work beautifully similar in a way you just need to exchange the method called, and the rest can stay the same.

Those two methods are a handy little tool if you want to test the array for something that has Boolean as a result.

Try to use it in your next project where it applies, or see if you find a way to refactor code in your current project where this way results in a much nicer and more readable code.

Photo by Frank Vessia on Unsplash

. . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player