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

node.jsLoopsunderscore.js

node.js Problem Overview


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.

node.js Solutions


Solution 1 - node.js

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

Solution 2 - node.js

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

Solution 3 - node.js

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1741851View Question on Stackoverflow
Solution 1 - node.jsPeter LyonsView Answer on Stackoverflow
Solution 2 - node.jsVishnu PSView Answer on Stackoverflow
Solution 3 - node.jspdoherty926View Answer on Stackoverflow