I am aware that I can simplify:
var a;
var b;
into:
var a, b;
But can I do the same on loops?
for(var a=0,b=0;a<3;a++){
//code
}
Or I need to write var a=0, var b=0
?
I am aware that I can simplify:
var a;
var b;
into:
var a, b;
But can I do the same on loops?
for(var a=0,b=0;a<3;a++){
//code
}
Or I need to write var a=0, var b=0
?
for(var a=0,b=0;a<3;a++)
In other programming languages like C/C++ it is widely used. There is no need to use var
twice - you've already stated that you are declaring variables with the first one.
You can also use (not a good practice):
var a = x, b = y; // or var a = x; var b = y;
for ( ; a < b; a++) {
//code
}
This is mostly used when the length
property is used. Thus not calling it on every iteration. Here is a related question, jsperf test, jsperf test.
for(var i = 0, len = obj.length; i < len; i++) {
//code
}
The syntax for using var
in the initialisation part of a for
statement is the same as using var
elsewhere. So the following will work fine:
for(var a=0,b=0; a<3; a++){ }
Note that this does not limit the scope of variables declared like that to just the for
statement's block as would happen in some other languages. JavaScript has only global and function scope, not block scope. The a
and b
variables declared in the example above will be accessible anywhere in the current scope (including above the for
statement, though the values will be undefined).
Note also that you can't say:
for(var a=0; var b=0; a<3; a++) { }
(If you want to declare multiple variables in the for
statement's initialisation expression you need to use the comma syntax.)