var
declares a variable as "local" to the function it's defined in.
Without var
, you works
variable is global : it can be seen/accessed/used from anywhere.
With var
, your notwork
variable is local to the foo
function : it cannot be seen/used from outside of that function.
For more informations, you can take a look at the documentation of the var
statement on MDC, which states (quoting) :
The scope of a variable is the current
function or, for variables declared
outside a function, the current
application.
Using var
outside a function is
optional; assigning a value to an
undeclared variable implicitly
declares it as a global variable.
However, it is recommended to always
use var
, and it is necessary within
functions in the following situations:
- If a variable in a scope containing the function (including the global
scope) has the same name.
- If recursive or multiple functions use variables with the same name and
intend those variables to be local.
Failure to declare the variable in
these cases will very likely lead to
unexpected results.