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 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Because _.each and a regular for () {} loop are not the same thing.
@ConAntonakos When you use for-each(collection, callback) in JS there isn't any for loop inside callback hence break/continue do not apply.
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.

Comments

0
_.each(users, function(u, index) {
  if (u.superUser) {
    //Some code
  }
});

2 Comments

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.
He was asking how to avoid that very poor practice of arrow-code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.