Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  115] [ 5]  / answers: 1 / hits: 16228  / 13 Years ago, wed, november 9, 2011, 12:00:00

Possible Duplicate:

Difference between using var and not using var in JavaScript






var foo = 1;

foo = 1;


What is the difference between above two lines ?


More From » javascript

 Answers
8

Basically, var declares a variable and you can also assign to it at the same time.



Without var, it's assigning to the variable. Assigning will either assign to an existing variable or create a global variable of that name then assign to it.



Outside of functions, that means there's no real difference (in principal) if the variable does not already exist. Both create the global variable foo in that case.



Within a function, there's a huge difference. The first creates a variable local to the function regardless of whether or not it exists elsewhere.



The second will create a global variable if it doesn't exist, or simply change the value if it does exist.



In order to keep code as modular as possible, you should always use var unless you are specifically wanting to change existing global variables. That means declaring all globals outside of functions with var and declaring all locals with var.


[#89228] Monday, November 7, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lailab

Total Points: 706
Total Questions: 102
Total Answers: 95

Location: Falkland Islands
Member since Mon, Jul 13, 2020
4 Years ago
;