.each function on Sitepoint's web site

Sitepoint has this example … it appears incorrect?

const arr = [

$.each(arr, function(index, value) {
  // Will stop running after "three"
  return (value !== 'three');

// Outputs: one two three

shouldn’t the return statement read:

return (index > 2);


return (value == ‘four’)

Just wondering.

Are you referring to this article?

Why do you think it is not working? It behaves exactly like it says it will. It will return

one two three
That’s because it will keep running until it returns false, which kicks it out of the loop, which it will when it gets to the fourth instance of the array


Yes and D. Maxwell below corrected my interpretation

1 Like

I will say it’s not the most readable solution, but it’s correct. (It’s unintuitive to try and say “I want this to stop, so I want a false”. Humans think best in the true → true scenario.)
Your instincts are somewhat correct, you could also have said return (index < 2), [again, keep in mind that the logic is backwards - we want “true” for continue and “false” for stop] or any other expression such that the return value on the third iteration loop is false.

1 Like

I DID have to copy it over to JSFiddle and run it, playing with it a little to understand what it’s supposed to do. I know I personally wouldn’t write it that way, for all the reasons @m_hutley gave. There are more elegant (or at the least, easier to read) ways to approach that problem.

1 Like