-2

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?

5 Answers5

2

for(var a=0,b=0;a<3;a++) is fine.

Ivan Castellanos
  • 8,041
  • 1
  • 47
  • 42
0

it is perfectly valid javascript and it will work as expected.

asawilliams
  • 2,908
  • 2
  • 30
  • 54
0

Yes,you can do like that. Just check it.

Sukanya
  • 1,041
  • 8
  • 21
  • 40
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
}
Community
  • 1
  • 1
Bakudan
  • 19,134
  • 9
  • 53
  • 73
  • @TuxedoKnightChess - Huh? This answers your question and then goes on to give a practical example - why would you want to downvote it? – nnnnnn Jan 06 '12 at 06:03
0

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.)

nnnnnn
  • 147,572
  • 30
  • 200
  • 241