Array.every() method in JavaScript
Learn how to use Array.every() method in JavaScript.
The every() method executes the callback function on each element present in the array and returns false immediately, if at least one element fails the test condition otherwise, it returns true.
Here we are using the every() method to check, whether all users belong to the same school or not.
const users1 = [
{id:1,user:"gowtham", school:"wim"},
{id:2,user:"king" ,school:"wim"},
{id:3,user:"nick",school:"rim"},
{id:4,user:"jim",school:"wim"},
]
// test condition
console.log(users1.every(user => user.school === "wim")) // falseIn the above example, user: nick has a different school name, so that test condition is failed and every() method returns false.
In this example, all users have the same school name, so that the test condition is passed and every() method returns true.
const users2 = [
{ id:1,user:"gowtham", school:"wim"},
{id:2,user:"king" ,school:"wim"},
{id:4,user:"jim",school:"wim"},
]
console.log(users2.some(user => user.school === "wim")) // trueChecking all numbers are even
We can use the every() to check whether all numbers in a given array are even or not.
const numbers = [2,4,6,8,10];
console.log(numbers.every(number => number % 2 === 0)) // trueSimilarly, we can use to check odd numbers.
const numbers = [1,3,5,7,9];
console.log(numbers.every(number => number % 2 === 1)) // trueImportant points
-
The
every()method only returnstrue, if all elements in the array pass the test condition. -
The
every()method returnsfalse, if at least one element in the array fails the test condition.


