The var statement allows you to explicitly declare a variable or variables. Here's the syntax of this statement:
var name_1 [ = value_1] [ ,..., name_n [= value_n]]
The var keyword is followed by a comma-separated list of variables to declare; each variable in the list may optionally have an initializer expression that specifies its initial value. For example:
var i; var j = 0; var p, q; var greeting = "hello" + name; var x = 2.34, y = Math.cos(0.75), r, theta;
The var statement defines each named variable by creating a property with that name either in the call object of the enclosing function or, if the declaration does not appear within a function body, in the global object. The property or properties created by a var statement cannot be deleted with the delete operator. Note that enclosing a var statement in a with statement does not change its behavior.
If no initial value is specified for a variable with the var statement, the variable is defined, but its initial value is undefined.
Note that the var statement can also appear as part of the for and for/in loops. For example:
for(var i = 0; i < 10; i++) document.write(i, "<br>"); for(var i = 0; j=10; i < 10; i++, j--) document.write(i*j, "<br>"); for(var i in o) document.write(i, "<br>");
If you attempt to read the value of an undeclared variable, JavaScript generates an error. If you assign a value to a variable that you have not declared with var, JavaScript implicitly declares that variable for you. Note, however, that implicitly declared variables are always created as global variables, even if they are used within the body of a function. To prevent the creation of a global variable (or the use of an existing global variable) when you meant to create a local variable to use within a single function, you must always use the var statement within function bodies. It's sest to use var for all variables, whether global or local.
Global variables are accessible everywhere, whereas local variables are only accessible within the current function scope. JavaScript does not have block scope, but it does maintain scope throughout a function, even if there are nested functions, etc… Inside a function block, local variables are defined with the var keyword. When the function ends, the variables are no longer available. If the var keyword was not used, the variables will be implicitly declared and made global.
A local variable takes precedence over a global variable of the same name. Be careful and understand that you can hide global variables within a function if using var on a variable of the same name as an existing global variable, and be extra careful because you can overwrite a global variable value if you decide not to use var. The best way to avoid problems is simple: DECLARE ALL VARIABLES WITH var.