If you want to do the tricky one-line for loop style, the "correct" syntax is:
var array = ['a', 'b', 'c'];
for (var i = 0, rowName; rowName = array[ i++ ]; ) {
console.log(rowName);
}
Notice the ending ; of the for loop declaration. There's technically an empty statement after the ; which is where you normally would do i++.
In this case, the "condition" of the for loop is taking advantage of the Javascript assignment operator. If you have some code like this:
var a;
if( a = 1 ) { // Note this is assignment = not comparison ==
console.log('true');
}
It will log "true". Why? Because inside of an expression, a = 1 actually returns 1. And 1 is "truthy," meaning it evaluates to true in a boolean context like an if statement.
The opposite is also true, if your value is falsey:
var a;
if( a = 0 ) {
console.log('true');
}
It will not log, because a = 0 is returning 0 (as well as assigning 0 to a). And 0 is falsey.
This whacky for-loop syntax is only for certain conditions:
- If any of the array elements are "falsey" (
null, undefined, "", etc) it will prematurely terminate the loop, because of how operators work as mentioned above.
- This assumes you don't care about the loop index
i. It will be off by 1 for every iteration of the loop, because i++ is executed before the for block. That is, the first time your for body executes, i will be 1, not its declared starting value of 0.
- The only benefit of this pattern is saving a few bytes. It's generally not used in the real world because of the above two pitfalls.
rowNameis undefined before then. See for @ MDNforloop isn't evaluated until the end of each iteration. If it were evaluated upfront to assignrowName, it would also immediately incrementito1, skipping the initial value of0.