šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

The Javascript every() array method explained

In a nutshell, the Javascript every() method will take each element from an array and test it against one logical condition. The every() method will return true if ALL the elements from that array satisfy the condition, or false if at least one element fails the condition.

For example, given the following array:

const arr = [10, 20 , 4, 3, 70]

The following every() example will return true:

let underOneHundred = arr.every((el) => {  
    return el < 100 
})

// underOneHundred is true

And given that an arrow function returns by default the last result we can just write:

const arr = [10, 20 , 4, 3, 70]
let underOneHundred = arr.every(el => el < 100)

// underOneHundred is true

The every() method makes it easy to test if all the elements in an array meet a given condition.

One more example could be:

const arr = [1, 3, 5, 2, 7]
let justOddNumbers = arr.every(el => el % 2)

// justOddNumbers is false

Alongside the actual element from the array, we can also get access to the index of that element and the full array:

const arr = [1]
arr.every( (el, index, a) => {
    // el is 1
    // index is 0
    // a is [1]
})

You may also be interested in reading about one of the most underused Javascript array methods: the reduce() method.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *