The preferred approach in 2016 is to declare the variable in the loop head, using let
:
for (let i = 0; i < max; i++) { }
^^^
There is probably minimal performance difference between this and other approaches, but there are major advantages in terms of the robustness and clarity of your code.
First, with let
, i
is local to the for
construct, so it can't "leak out", or modify some other i
in an outer scope.
Second, and perhaps more importantly, a new version of i
is created for each iteration of the loop. In technical terms, "you get a fresh binding for each iteration if you let-declare a variable" (see this excellent article). This solves the age-old problem of closures created inside the for-loop using the final value of i
. We can now just write
for (let i = 0; i < 10; i++) {
setTimeout(() => alert(i), i * 1000);
}
instead of having to do some clumsy work-around such as
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(() => alert(i), i * 1000);
}(i));
}
which has been the topic of countless questions here on SO, and which many of you have wasted far too many brain cycles learning.