mattHunting10 mattHunting10 - 2 months ago 7
Javascript Question

writing the Array.every() function

I am wondering how you can write the

Array.every()
function yourself, with a for loop. In my example the for loop will print true 5 times for each iteration. How can I make it return true just once if all values pass, like the
Array.every()
function?

var array = [1,2,3,4,5];

console.log(array.every(function(num){return num < 6}))

// the for loop will return true 5 times
for(i=0;i<array.length;i++){
if(array[i] < 6)
console.log(true)
}

Answer

"In my example the for loop will return true 5 times for each iteration."

No it won't, because the first return statement returns immediately without iterating over the rest of the items. So really what you've implemented is a simple version of the .some() method, which returns true if at least one item matches the condition.

If you just want a simple for loop implementation to test that every item matches the condition, reverse the test logic and return false as soon as you find an element that does not match. And if no items in the loop fail the test then the loop will complete so return true afterwards:

for(i=0;i<array.length;i++){
  if(!(array[i] < 6))
    return false;
}
return true;

You may like to take a look at a full implementation of .every(): MDN's .every() polyfill