0

From my experience, if you want to exit a jQuery each loop you need to use return true or return false to continue or break respectfully.

$.each([1,2,3,4], function( index, value ) {
  if (value == 1) {
    // This will make us jump to the next value (continue)
    return true; 
  } else {
    //This will make us exit the loop (break)
    return false; 
  }
  console.log('This will never print');
});

But in vanilla JS you can use directly continue and break, and you can use return to exit the function all together.

for (i = 1; i < 4; i++) {
  if (i === 1) {
    // This will make us jump to the next value
    continue; 
  } else {
    //This will make us exit the loop
    break; 
  }
  console.log('This will never print');
}

Why is that?

And also, can you exit a jQuery loop by returning immediately, without having to pass a value to a local variable?


NOTE

Has a frequent user (although not much of a giver back) I really didn't enjoy having my question marked as duplicated, since my question is not the same as the one suggested by Ryan Wilson and David.

My question is more to the core of WHY it has that behaviour and not so much as to HOW to solve it.

  • `continue` and `break` work only in normal loops, whereas `.each` is a *method call* where you supply *a callback function*, so you're not in the context of an actual loop structure. [This question](https://stackoverflow.com/questions/2641347/short-circuit-array-foreach-like-calling-break) goes into the details of the vanilla JS `.forEach` but it's applicable for the jQuery `.each` as well. – VLAZ Jul 15 '20 at 20:19
  • 1
    Please show examples of these loops you're talking about. Note that the source code for jQuery is available on their GitHub site. For instance, [the source for `jQuery.each`](https://github.com/jquery/jquery/blob/b502866960b30863e56968bd35e720905ac58025/src/core.js#L238) – Heretic Monkey Jul 15 '20 at 20:19
  • @VLAZ Except you can't break out of `.forEach` :) – Heretic Monkey Jul 15 '20 at 20:20
  • @HereticMonkey that's true. Small difference to jQuery. Still understanding how the iteration methods work will ultimately make the jQuery iteration methods trivial to reason for as well. – VLAZ Jul 15 '20 at 20:23
  • @HereticMonkey Thank you for the answer. I understand the reason now (and I also understand my question was a bit lazy). Looking at the source code really did it for me. – João Pereira Rosa Jul 15 '20 at 23:02

0 Answers0