While exiting from each
loop- return 0
is not working. However, changing it to return false
works perfectly.
The regular JavaScript loops (while,for) exits fine by return 0
. Doesn't it breaks the uniformity!
While exiting from each
loop- return 0
is not working. However, changing it to return false
works perfectly.
The regular JavaScript loops (while,for) exits fine by return 0
. Doesn't it breaks the uniformity!
We can break the
$.each()
loop at a particular iteration by making the callback function returnfalse
. Returning non-false is the same as acontinue
statement in a for loop; it will skip immediately to the next iteration.
The difference is simply that 0
is not the exact same thing as false
.
Usually when a boolean value is required any value will be usable, and it will be converted to a boolean. In that case the 0
would be converted to false
.
In a jQuery $.each
loop that wouldn't work. If you don't specifically return anything from a function, then the return value is undefined
. If that would be converted to a boolean that would also become false
.
The $.each
method doesn't convert the return value to a boolean, it specifically looks for the value false
. Any other value will let the loop continue.
Simply put, 0 !== false.
In your own code, you may sometimes check for a false-like answer:
0 == false; // true
null == false; // true.
However, jQuery (rightly so) uses a strict equality (===) operator.
As such:
0 === false; // false
null === false; // false
false === false; // true
This if fundamentally an identity vs equality issue: Which equals operator (== vs ===) should be used in JavaScript comparisons?
To break a $.each
loop, you have to return false
in the loop callback.
Returning anything else skips to the next iteration, equivalent to a
continue
in a normal loop.
Using return 0, will return zero, which is a number. Using return false says that there is nothing to return, or don't return.