Home  >  Q&A  >  body text

What is the meaning of the `return` keyword in the `forEach` function?

<p><br /></p> <pre class="brush:js;toolbar:false;">$('button').click(function () { [1, 2, 3, 4, 5].forEach(function (n) { if (n == 3) { // This should break and nothing should pop up return false } alert(n) }) })</pre> <pre class="brush:html;toolbar:false;"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> ;</script> <button>Click me</button></pre> <p><br /></p> <p>My question is: Why does it still pop up the next number even though I call <code>return</code>? Like: <em>Ignore the code below and continue to the next element</em></p>
P粉964682904P粉964682904401 days ago525

reply all(2)I'll reply

  • P粉245003607

    P粉2450036072023-08-22 14:50:44

    The return statement return will exit the current function, but the loop will continue, so you will get the "next" skipped if statement and pop 4 Item...

    If you need to stop the loop, you should use a normal for loop like this:

    $('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 break and continue in js here: http://www.w3schools.com/js/js_break.asp

    reply
    0
  • P粉461599845

    P粉4615998452023-08-22 11:56:31

    From Mozilla Developer Network:

    reply
    0
  • Cancelreply