how to stop Javascript forEach?

04/29/2020 06:00:02

i'm playing with nodejs and mongoose — trying to find specific comment in deep comments nesting with recursive func and foreach within. Is there a way to stop nodejs 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;
    });
}

Verified Answer (890 Votes)

06/07/2011 10:18:04

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.

890

Answer #2 (46 Votes)

06/07/2011 10:12:49

Breaking out of Array#forEach is not possible. (You can inspect the source code that implements it in Firefox on the linked page, to confirm this.)

Instead you should use a normal for loop:

function recurs(comment) {
    for (var i = 0; i < comment.comments.length; ++i) {
        var subComment = comment.comments[i];
        recurs(subComment);
        if (...) {
            break;
        }
    }
}

(or, if you want to be a little more clever about it and comment.comments[i] is always an object:)

function recurs(comment) {
    for (var i = 0, subComment; subComment = comment.comments[i]; ++i) {
        recurs(subComment);
        if (...) {
            break;
        }
    }
}
46

Answer #3 (33 Votes)

10/04/2012 15:03:10

In some cases Array.some will probably fulfil the requirements.

33
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.