Actually, it's
for ([initialization]; [condition]; [final-expression])
where all three expressions are optional.
In this case, i--
is a condition, when it reaches 0
it's falsy, and the loop stops.
The "final-expression"
is the one not used here.
var arr = [1, 2, 3, 4];
for (var i = arr.length; i--;) {
console.log(arr[i]);
}
The for
statement sets the value of i
to a positive integer, then on each iteration it evaluates the condition, effectively decrementing i
until it reaches a number that is falsy, which happens when i
reaches zero.
Here's some other examples of how to skip expressions in a for
loop
Skipping the initialization
var i = 0;
for (; i < 4; i++) {
console.log(i);
}
Skipping the condition
for (var i = 0;; i++) {
console.log(i);
if (i > 3) break;
}
Skipping everything
var i = 0;
for (;;) {
if (i > 4) break;
console.log(i);
i++;
}