javascriptloopsforeachbreakcontinue

How to simulate a loop's 'break' statement inside an array-iterating, custom implemented, 'forEach' function/method?


What is the best way to implement a simulation of a loop's break statement, when one does iterate through a user/engine defined function?

forEach([0, 1, 2, 3, 4], function (n) {
  console.log(n);
  
  if (n === 2) {
    break;
  }
});

I've thought of implementing forEach in a way that would break when the function returns false. But I would like to hear thoughts on how that is normally done.


Solution

  • returning false is the most common way to do it. That's what jQuery's iterator function .each() does:

    We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

    And its very simplified implementation:

    each: function( object, callback ) {
      var i = 0, length = object.length,
      for ( var value = object[0]; 
            i < length && callback.call( value, i, value ) !== false; // break if false is returned by the callback 
            value = object[++i] ) {}
      return object;
    }