Scope of variables
It's important to note, especially if you have come to JavaScript from another language, that variables in JavaScript are not defined in a block scope, but in a function scope. This means that if a variable is defined inside a function, it's not visible outside of the function. However, if it's defined inside an if
or a for
code block, it's visible outside the block. The term global variables describes variables you define outside of any function (in the global program code), as opposed to local variables, which are defined inside a function. The code inside a function has access to all global variables as well as to its own local ones.
In the next example:
The
f()
function has access to theglobal
variableOutside the
f()
function, thelocal
variable doesn't existvar global = 1; function f() { var local = 2; global++; return global; }
Let's test this:
> f(); 2 ...