0

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) 
}
2

1 Answer 1

1

"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

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I meant to say if i console.log() it will print out 5 times. This is what I needed thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.