262

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

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Tân
  • 1
  • 15
  • 56
  • 102

2 Answers2

373

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.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
squaleLis
  • 6,116
  • 2
  • 22
  • 30
  • 65
    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`). – Ronen Cypis Jan 07 '16 at 11:30
  • 10
    I agree with @RonenCypis ... And suggest you to use `some()` – squaleLis Jan 07 '16 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 '20 at 17:30
  • 5
    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. – MattTreichel Sep 23 '21 at 16:03
58

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

Ronen Cypis
  • 21,182
  • 1
  • 20
  • 25
  • 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 :-) – Ronen Cypis Jan 07 '16 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 07 '16 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 :-) – Ronen Cypis Jan 07 '16 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 04 '18 at 13:22
  • Original code has alert on 1,2,4,5. It misses 3. - 10 feb 2022 -firefox 97. – JoePythonKing Feb 10 '22 at 23:07