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; }); }
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
You can't break from a forEach .
Officially, there is no proper way to break out of a forEach loop in javascript. Using the familiar break syntax will throw an error. If breaking the loop is something you really need, it would be best to consider using a traditional loop.
You use the break statement to terminate a loop early such as the while loop or the for loop. If there are nested loops, the break statement will terminate the innermost loop. You can also use the break statement to terminate a switch statement or a labeled statement.
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.
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; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With