how to stop Javascript forEach?

kulebyashik picture kulebyashik · Jun 7, 2011 · Viewed 542.2k times · Source

I'm playing with Node.js and Mongoose — trying to find specific comment in deep comments nesting with recursive function and forEach within. Is there a way to stop Node.js forEach? As I understand every forEach iteration is a function and and I can't just do break, only return but this won't stop forEach.

function recurs(comment) {
    comment.comments.forEach(function(elem) {

        recurs(elem);

        //if(...) break;

    });
}

Answer

slezica picture slezica · Jun 7, 2011

You can't break from a forEach. I can think of three ways to fake it, though.

1. The Ugly Way: pass a second argument to forEach to use as context, and store a boolean in there, then use an if. This looks awful.

2. The Controversial Way: surround the whole thing in a try-catch block and throw an exception when you want to break. This looks pretty bad and may affect performance, but can be encapsulated.

3. The Fun Way: use every().

['a', 'b', 'c'].every(function(element, index) {
  // Do your thing, then:
  if (you_want_to_break) return false
  else return true
})

You can use some() instead, if you'd rather return true to break.