Modifying items in an array using array.every()

**Hi, i saw this code on MDN while i was trying to understand array.every(), can someone please break it down to me. I don’t understand why it’s iterating 3times when return value is elem < 2 **

Your code so far


// Modifying items
let arr = [1,2,3,4];
arr.every((elem,index,arr)=>{
  arr[index+1]-=1
  console.log(`[${arr}][${index}] -> ${elem}`)
  return elem < 2 
})
// Loop runs upto three iterations, which would've ran two times without any modification
// 1st iteration: [1,1,3,4][0] -> 1
// 2nd iteration: [1,1,2,4][1] -> 1
// 3rd iteration: [1,1,2,3][2] -> 2






Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/comment-your-javascript-code/

Array.prototype.every()

method in JavaScript ensures if all the array element passes the test specified by the call back function. In your case, the array has 4 elements. For the first 2 elements, every() method returns true as they are less than 2. But for the third element, which is not less than 2, every() method returns false and loop breaks.

1 Like