DEV Community

claudemotoba
claudemotoba

Posted on

Use every() and some() to test the elements of your arrays

In this tutorial I will explain to you how to test if the elements of the arrays fulfill a condition using the some () and every method of javascript.

some()

The some() method allows you to test if at least one element of the array passes the test implemented by the function. Its return value is a boolean which indicates the result of the test.

"use strict"

const users = [
    { name: "claude Motoba", sexe: "M", age: 19, skills: "Fullstack" },
    { name: "Diana Jade", sexe: "F", age: 25, skills: "Frontend" },
    { name: "Erik Johnson", sexe: "M", age: 18, skills: "Backend" },
];

const test = users.some(({ age, skills }) =>{ 
    return age >= 18 && skills == "Fullstack";
})

console.log(test) // log true
Enter fullscreen mode Exit fullscreen mode

every()

every() on the other hand allows us to test if all the elements of the array pass the test implemented by the function. It also has as return value a boolean which indicates the result of the test.

"use strict"

const users = [
    { name: "claude Motoba", sexe: "M", age: 19, skills: "Fullstack" },
    { name: "Diana Jade", sexe: "F", age: 25, skills: "Frontend" },
    { name: "Erik Johnson", sexe: "M", age: 18, skills: "Backend" },
];

const test = users.every(({ sexe, age }) =>{ 
    return sexe == "M" && age >= 18;
})


console.log(test) // log false
Enter fullscreen mode Exit fullscreen mode

Conclusion

The difference between the two is that the some () method tests whether a single element fulfills the condition while every () checks all the elements.

Top comments (0)