Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Whether it is Java, C#, C++ syntax for the for loop looks like that:

    for (int i = 1; i <= 5; i++)
    {
        // something
    } 

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?

share|improve this question

closed as off-topic by Jamal May 4 at 22:12

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions must involve real code that you own or maintain. Questions seeking an explanation of someone else's code are off-topic. Pseudocode, hypothetical code, or stub code should be replaced by a concrete example." – Jamal
If this question can be reworded to fit the rules in the help center, please edit the question.

    
Possible duplicate of codereview.stackexchange.com/q/43371/32103 –  megawac May 4 at 22:42
    
Just drop the var in the second loop, and you are good. Though, if you are going for proper & maintainable code, then you should extract the var into it's own line so that the scope is clearer. –  konijn May 5 at 12:31
add comment

Browse other questions tagged or ask your own question.