mattHunting10 mattHunting10 - 1 year ago 85
Javascript Question

writing the Array.every() function

I am wondering how you can write the

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

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

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

// the for loop will return true 5 times
if(array[i] < 6)

Answer Source

"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:

  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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download