[Solved-5 Solutions]How to short circuit array.forEach like calling break ? - javascript tutorial



Problem:

[1,2,3].forEach(function(el) {
    if(el === 1) break;
});

How can we do this using the new forEach method in JavaScript ?

Solution 1:

There's no built-in option to break in forEach. To interrupt execution we would have to throw an exception of some sort.

var BreakException = {};

try {
  [1, 2, 3].forEach(function(el) 
  {
    console.log(el);
    if (el === 2) throw BreakException;
  });
 } 
 catch (e) 
 {
  if (e !== BreakException) throw e;
 }

Use Array#some:

[1, 2, 3].some(function(el) {
  console.log(el);
  return el === 2;
});

This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.

Read Also

PHP Foreach Loop

Solution 2:

We can use every method:

[1,2,3].every(function(el) {
    return !(el === 1);
});

For old browser support this below code:

if (!Array.prototype.every)
{
  Array.prototype.every = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this &&
          !fun.call(thisp, this[i], i, this))
        return false;
    }

    return true;
  };
}

Solution 3:

This code does not print the array elements after the number 5:

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let el of arr) {
  console.log(el);
  if (el === 5) {
    break;
  }
}

Solution 4:

Consider to use jquery's each method, since it allows to return false inside callback function:

$.each(function(e, i) { 
   if (i % 2) return false;
   console.log(e)
})

Lodash libraries provides takeWhile method that can be bound with map/reduce/fold etc:

var users = [
  { 'user': 'wiki',  'active': false },
  { 'user': 'techy',    'active': false },
  { 'user': 'wikitechy', 'active': true }
];

_.takeWhile(users, function(o) { return !o.active; });
// => objects for ['wiki', 'techy']

// The `_.matches` iteratee shorthand.
_.takeWhile(users, { 'user': 'wiki', 'active': false });
// => objects for ['wiki']

// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(users, ['active', false]);
// => objects for ['wiki', 'techy']

// The `_.property` iteratee shorthand.
_.takeWhile(users, 'active');
// => []

Solution 5:

Here we can use Array.prototype.find method:

[1, 2, 3].find(function(el) {
    return el === 2;
}); // returns 2


Related Searches to How to short circuit array.forEach like calling break ? - javascript tutorial