I see two differents way for declaring variables when making a “for loop” in javascript:
First way:
for (var i = 0, l = [].length; i < l; i += 1) {
// make something
}
Second way:
var i;
var l;
for (i = 0, l = [].length; i < l; i += 1) {
// make something
}
Is there some reason to prefer one of these?
They are same, you can use either BUT first is more readable and terse.
The point is that variables in both cases are local with the presence of
varkeyword. With first method also, you create two local variables:Instead of
Why use
varkeyword again and again when only one can do it. In fact that turns out to be one of the good practices of JS.