What does `return` keyword mean inside `forEach` function?

JavascriptArrays

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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: > > - A simple loop > - A for...of > loop > - Array.prototype.every() > - Array.prototype.some() > - Array.prototype.find() > - Array.prototype.findIndex() > > 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.

Solution 2 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionT&#226;nView Question on Stackoverflow
Solution 1 - JavascriptsqualeLisView Answer on Stackoverflow
Solution 2 - JavascriptRonen CypisView Answer on Stackoverflow