user784637
user784637

Reputation: 16142

What does the syntax in this two expression for loop mean?

What do the two expressions var i = 0, item; item = a[i++]; mean?

for (var i = 0, item; item = a[i++];) {  
    // Do something with item  
}  

Apparently this is an alternative to

for (var i = 0; i < a.length; i++) {  
    // Do something with a[i]  
}  

Upvotes: 1

Views: 149

Answers (1)

Adam Rackis
Adam Rackis

Reputation: 83356

for (var i = 0, item; item = a[i++];) {  
    // Do something with item  
} 

Is telling the loop to keep going so long as item gets assigned a "truthy" value. After each iteration, item is assigned the next item in the array. The idea is that once i gets to a point where it's beyond the bounds of the array, undefined will be assigned, and the loop will terminate.

But whoever wrote this code should be fired since the loop will also terminate if the array contains any "falsy" values: 0, empty string, false Ok, this code was written by the Mozilla folks, and they're much smarter than I am. Just note that the loop will terminate if the array contains any "falsy" values: 0, empty string, false

To see for yourself:

var a = [1, 2, 3, 0, 5, 6];

for (var i = 0, item; item = a[i++]; ) {
    alert(item);
} 

note that the loop terminates after 3, since 0 is falsy.

Upvotes: 6

Related Questions