What does `return` keyword mean inside `forEach` function? [duplicate]
Asked Answered
S

2

273

$('button').click(function () {
   [1, 2, 3, 4, 5].forEach(function (n) {
      if (n == 3) {
         // it should break out here and doesn't alert anything after
         return false
      }
      alert(n)      
   })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me</button>

My question: Why does it still alert next number although I call return? Just like: Ignore the code below and continue with next element

Sodamide answered 7/1, 2016 at 11:8 Comment(4)
What about $('button').click(function(){})?Banc
You can break it using if(n>=3){ return falseCentuple
return doesn't break a loop, the break does!Subminiature
Interestingly the behavior of the example is much different if you alter line 2 and assign the array to a variable first like: var r = [1, 2, 3, 4, 5]; r.forEach(function (n) {. In this case it will break out of the loop.Ashworth
L
387

From the Mozilla Developer Network:

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.

Early termination may be accomplished with:

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

Langmuir answered 7/1, 2016 at 11:10 Comment(4)
Using forEach, and trowing an error to stop the iteration is a very bad practice, and is a real overkill. In your case you don't really want to iterate all of the array (forEach...), but you want to run until certain statement is met. You should use a simple loop for it (while, for, for in, do while).Rehabilitate
I agree with @RonenCypis ... And suggest you to use some()Langmuir
Everybody's got a plan until new Array(5) shows up.... (new Array(5)).every(e => e === "maybe for loop + break wasn't such a bad idea after all?") produces surprising results due to sparse arrays.Mcminn
This doesn't seem to answer the question of what return actually does in practice for a forEach loop, but I guess the next answer helps.Mailbag
R
61

The return exits the current function, but the iterations keeps on, so you get the "next" item that skips the if and alerts the 4...

If you need to stop the looping, you should just use a plain for loop like so:

$('button').click(function () {
   var arr = [1, 2, 3, 4, 5];
   for(var i = 0; i < arr.length; i++) {
     var n = arr[i]; 
     if (n == 3) {
         break;
      }
      alert(n);
   })
})

You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp

Rehabilitate answered 7/1, 2016 at 11:10 Comment(6)
What do you mean??? I wrote it like that for the ease of understanding... The code could be shortened a bit maybe, but it gets exactly what you wanted, without extra iterations of the array like some other answers here :-)Rehabilitate
You need to declare array before. You want to use a loop within the array length. You need an index to access array element..... So many things :) That's I meanPerforation
you've already declared the array in your example, i just added a reference (var arr) to it for easy access. You can also change the for loop to for in, or while... all of those options are much better, and faster then creating a new function, and throwing an error in your other examples here. Both performance wise, and clean-code... good luck anyway :-)Rehabilitate
This answer cleared up my exact question about whether it still sometimes makes sense to return inside a forEach loop, which it absolutely does when you don't want the remainder of your loop logic to be executed given a certain condition!Reseda
Original code has alert on 1,2,4,5. It misses 3. - 10 feb 2022 -firefox 97.Bankston
So basically return statement doesn't do anything except for that specific condition n==3. Not cool behavior.Divulge

© 2022 - 2024 — McMap. All rights reserved.