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 ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Basically,
vardeclares 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
fooin 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
varunless you are specifically wanting to change existing global variables. That means declaring all globals outside of functions withvarand declaring all locals withvar.