How to 'continue' inside a each loop : underscore, node.js

user1741851 picture user1741851 · Sep 6, 2013 · Viewed 50.6k times · Source

The code in node.js is simple enough.

_.each(users, function(u, index) {
  if (u.superUser === false) {
    //return false would break
    //continue?
  }
  //Some code
});

My question is how can I continue to next index without executing "Some code" if superUser is set to false?

PS: I know an else condition would solve the problem. Still curious to know the answer.

Answer

Peter Lyons picture Peter Lyons · Sep 6, 2013
_.each(users, function(u, index) {
  if (u.superUser === false) {
    return;
    //this does not break. _.each will always run
    //the iterator function for the entire array
    //return value from the iterator is ignored
  }
  //Some code
});

Side note that with lodash (not underscore) _.forEach if you DO want to end the "loop" early you can explicitly return false from the iteratee function and lodash will terminate the forEach loop early.