254

$('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

4
  • What about $('button').click(function(){})?
    – PDKnight
    Jan 7, 2016 at 11:09
  • You can break it using if(n>=3){ return false Jan 7, 2016 at 11:14
  • 1
    return doesn't break a loop, the break does! Feb 27, 2020 at 13:07
  • 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. Jun 18, 2020 at 13:18

2 Answers 2

358

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.

4
  • 62
    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). Jan 7, 2016 at 11:30
  • 10
    I agree with @RonenCypis ... And suggest you to use some()
    – squaleLis
    Jan 7, 2016 at 11:37
  • 2
    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.
    – yurisich
    Nov 19, 2020 at 17:30
  • 4
    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. Sep 23, 2021 at 16:03
52

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

5
  • 4
    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 :-) Jan 7, 2016 at 11:27
  • 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 mean
    – Tân
    Jan 7, 2016 at 11:31
  • 5
    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 :-) Jan 7, 2016 at 11:35
  • 4
    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!
    – GrayedFox
    Dec 4, 2018 at 13:22
  • Original code has alert on 1,2,4,5. It misses 3. - 10 feb 2022 -firefox 97. Feb 10, 2022 at 23:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.