Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between two array iterations

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
}
like image 752
richie Avatar asked Dec 27 '22 15:12

richie


2 Answers

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.

like image 167
nneonneo Avatar answered Dec 29 '22 07:12

nneonneo


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

like image 33
cbayram Avatar answered Dec 29 '22 06:12

cbayram