Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop Javascript forEach? [duplicate]

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;      }); } 
like image 716
kulebyashik Avatar asked Jun 07 '11 05:06

kulebyashik


People also ask

How do you stop a forEach loop?

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.

Can we use break in forEach JavaScript?

You can't break from a forEach .

Can we stop 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.

How do you stop a loop in JavaScript?

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.


2 Answers

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.

like image 187
slezica Avatar answered Sep 20 '22 11:09

slezica


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;         }     } } 
like image 26
Domenic Avatar answered Sep 19 '22 11:09

Domenic