Im just wondering the difference between these array iterations, and why the second one seems to be really rarely used, is something wrong with it?
var items = [ /*...*/ ]
for (var i = 0; i < items.length; i++) {
var item = items[i];
// Do some stuff with the item
}
The second way:
var items = [ /*...*/ ]
for (var i, item; item = items[i]; i++) {
// Do some stuff with the item
}
The first one is guaranteed to always iterate through every element.
The second one would stop midway if it encounters some false-like element, such as 0.
In the second for loop you need to initialize your i variable.
Consider:
var items = ["string", false, null, 0, "", {}, []];
First loop will loop through the entire array. However, second loop's conditional will evaluate the value assigned to item. The boolean value of this portion would be:
!!(item = items[i])
valid values such as null, 0, false, ""(empty string) and undefined will evaluate to false and break. In the array above, you'll break out of the for loop when item is assigned to false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With