Whether it is Java, C#, C++ syntax for the for loop looks like that:
for (int i = 1; i <= 5; i++)
{
// something
}
- http://www.cplusplus.com/doc/tutorial/control/
- http://msdn.microsoft.com/en-us/library/ch45axte.aspx
- http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
But in Javascript scope works differently: http://stackoverflow.com/questions/500431/javascript-variable-scope
I would like to implement two for-loops and my first / intuitive / maybe naive syntax would be:
for (var i=0; i<10; i++) {
}
for (var i=0; i<10; i++) {
}
But it is not correct, see http://www.jshint.com/
'i' is already defined.
Would it be better to have it that way:
var i;
for (i=0; i<10; i++) {
}
for (i=0; i<10; i++) {
}
I don't feel like adding an extra line so I wonder how do you handle multiple loops in javascript, what is the recommended way here?
var
in the second loop, and you are good. Though, if you are going for proper & maintainable code, then you should extract thevar
into it's own line so that the scope is clearer. – konijn May 5 at 12:31