by Sai gowtham

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")) //  false

In 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")) //  true

Checking 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)) // true

Similarly, we can use to check odd numbers.

const numbers = [1,3,5,7,9];

console.log(numbers.every(number => number % 2 === 1)) // true

Important points

  • The every() method only returns true, if all elements in the array pass the test condition.
  • The every() method returns false, if at least one element in the array fails the test condition.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course