Array.every() method in JavaScript

Array.every() method in JavaScript

In this post we will give you information about Array.every() method in JavaScript. Hear we will give you detail about Array.every() method in JavaScriptAnd how to use it also give you demo for it if it is necessary.

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 conditionconsole.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.

Hope this code and post will helped you for implement Array.every() method in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US