[javascript] What does `return` keyword mean inside `forEach` function?

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

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

This question is related to javascript arrays

The answer is


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