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 *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X