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.