Javascript Array.Some() method with examples

July 15, 2020

#Javascript #Array #Some

Javascript some() method is a function that you can apply on an Array in order to find if at least one element satisfies a certain condition.
In other words, it applies a given function to each element of an array and it returns a Boolean Value :

True => At least one element satisfies that function πŸ‘
False => No element satisfies that function πŸ‘Ž

It’s really simple and of course you can reach the same result with other functions, but it really improves code readability.
The most relevant benefit is the fact that the some() function will immediately return true once it finds a satisfying element and it will avoid to check the others elements.

Examples please!

We have a list of users and we would like to know if some of them is older than 80:

const users = [
    {
        name: 'Luke',
        age: 34
    },
    {
        name: 'Anthony',
        age: 82
    },
    {
        name: 'Mark',
        age: 57
    }
];

// Is someone older than 80 ?

users.some( user => user.age > 80 ); // True

We can get the same result using a for loop, but pay attention:

const users = [
    {
        name: 'Luke',
        age: 34
    },
    {
        name: 'Anthony',
        age: 82
    },
    {
        name: 'Mark',
        age: 57
    }
];

// Is someone older than 80 ?

let result = false;
for ( let i = 0; i < users.length ; i++ ) {

    if(users[i].age > 80){
        result = true;
        break; // πŸ‘ˆ Look at this line
    }

};

console.log(result); // true

If we don’t put the break, the for loop will continue to iterate over the array and it will be only a time consuming task.

Why use Array.some()

As you can see from this really simply examples, we wrote all the logic in a single line instead of 7 lines.
So if you use the some method you will write less code and this will improve the general code maintainability and readability.
Plus you don’t need worry to worry about breaking the loop at the right moment because it will be handled by the some() function itself.

Hope you enjoy this post, here you can find the official documentation.

Pingu 🐧


Written by Pingu who lives and works in Genoa building useful modern applications.

Something to share ?