Variable Declaration Necessary In For Loop?
What is the difference between: for (var i=0; i<5; i++) {} for (i=0; i<5; i++) {} And is it necessary to include the var keyword? I understand that the var keyword affects
Solution 1:
In the second example, your variable is defined globally, so if you're in the browser environment, you can access it from the window
object.
The first one is an equivalent of:
var i;
for (i=0; i<5; i++) {}
as all the variables in javascript are hoisted to the beginning of the scope.
Solution 2:
1
for (var i = 0; i < 5; ++i) {
// do stuff
}
2
var i;
for (i = 0; i < 5; ++i) {
// do stuff
}
3
for (i = 0; i < 5; ++i) {
// do stuff
}
1 and 2 are the same.
3 you probably never mean to do — it puts i
in the global scope.
Solution 3:
I am assuming your are using C#, Java or JavaScript. The short answer is you need the var if "i" has not already been declared. You do not need if it has already been declared.
For example:
var i;
for(i=1;i<=5;i++) {}
Now there may be some implicit variable typing depending on language and IDE, but relying on implicit typing can be difficult to maintain.
Hope this helps, good luck!
Post a Comment for "Variable Declaration Necessary In For Loop?"