0

Statement 1

var i = 0;
for (; i < 10 ; i++);

Statement 2

for (var i = 0 ; i < 10 ; i++);

Are those two statements equal?

sam ro
  • 11
  • 2
  • Yes they are equal and will work in the same way. – raw_orb Sep 17 '14 at 10:13
  • 1
    Yep, they are equal. All members in [`for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) are optional. – Teemu Sep 17 '14 at 10:14
  • @Teemu If all members in the for loop are optional, Does that not infact mean you could just use for(); and it would still be valid, however utterly useless that would be – Liam Sorsby Sep 17 '14 at 10:16
  • @LiamSorsby Actually the semicolons are required, then it would be just an infinite loop. – Teemu Sep 17 '14 at 10:18
  • @Teemu are there any known usages of the for loop with no parameters but semi-colons. It would be rather interesting to see. – Liam Sorsby Sep 17 '14 at 10:19
  • 1
    You could still `break;` out of a infinite loop: `var i=0; for(;;){i++; if(i >= 10){break;}}` – Cerbrus Sep 17 '14 at 10:19
  • 1
    @LiamSorsby You can use it where ever an infinite loop is needed, for example instead of `while(true){}`. Ofcourse nobody wants really infinite loops, but the conditions for breaking the loop can be checked within the body of the loop, as Cerbrus has shown above. – Teemu Sep 17 '14 at 10:21
  • possible duplicate of [JavaScript variables declare outside or inside loop?](http://stackoverflow.com/questions/3684923/javascript-variables-declare-outside-or-inside-loop) – Qantas 94 Heavy Sep 17 '14 at 11:32

2 Answers2

4

Nope, no difference between the 2 examples, functionally.

However, statement 2 can cause confusion. This is because i is not scoped to the for block, it's accessible outside of that for loop, which can result in a polluted global scope.

Just make sure you keep track of your variables when using them like statement 1.
Personally, I prefer something like this:

var i;

for(i = 0; i < 10; i++){
    // Do stuff
}

for(i = 0; i < 20; i++){
    // Do other stuff
}

This way, you'll always have your iterator properly set.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
0

There are no specific differences. Javascript's variable's scope is different from other languages like C#. This is already discussed here

Community
  • 1
  • 1
Thangadurai
  • 2,573
  • 26
  • 32
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Sid M Sep 17 '14 at 10:36
  • @Sid M, Agreed. But, the answer to the question is already there. And describing the same thing again from another post (as if that I found it) is IMHO "plagiarism" – Thangadurai Sep 17 '14 at 11:05