80

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.

3 Answers3

139
_.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.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
12

Instead of continue statement in for loop you can use return statement in _.each() in underscore.js it will skip the current iteration only.

Vishnu PS
  • 221
  • 2
  • 4
0
_.each(users, function(u, index) {
  if (u.superUser) {
    //Some code
  }
});
pdoherty926
  • 9,895
  • 4
  • 37
  • 68
  • Sorry. I should have put scenario in detail. I need to execute some code if super user is false and then continue. There will be another condition say, if (superUser != false && activated) for which I need to do something else and execute "Some code" and then there's else for which I need to execute "Some code". I just wanted to know if there's a way to do it without rewriting same code inside both else if and else. I do not want to create another function for this. –  Sep 06 '13 at 06:23
  • 1
    He was asking how to avoid that very poor practice of arrow-code. – David Betz Dec 24 '13 at 02:08