Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  176] [ 7]  / answers: 1 / hits: 24780  / 15 Years ago, sun, april 26, 2009, 12:00:00

What's the difference between:



function bar()
{
for (x=0; x< 100; x++) {}
}


And



function bar()
{
var x;
for (x=0; x< 100; x++) {}
}


If x wasn't declared outside of that function, and so it wasn't a global variable? I always wonder this because I generally don't declare throwaway variables which are used only in a loop, but I wonder if this might break comparability in a browser or such.


More From » javascript

 Answers
102

The first example will either add or modify the global variable x, which is generally to be avoided if not the desired outcome.



While your second example works as desired (no side effects) an alternative that looks better in my opinion would be



function bar()
{
for (var x=0; x< 100; x++) {}
}

[#99643] Monday, April 20, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tai

Total Points: 466
Total Questions: 87
Total Answers: 116

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;