in your program. On the other hand, if you declare a variable within a function body,
then you declare a local variable, which has local scope. This is also called function
scope in JavaScript because such a variable is defined only within the function bo dy
in which it is declared. Note that func tion parameters act as local variables and are
thus only accessible within the function body.
Now, a question ar ises: w hat if there are two variables, one local and the other g lobal,
using the same name? According to the just-mentio ned rules, both should be a cces-
sible within the function body in which the loc al variable is declared. To solve the
conflict, th ere’s an additional rule which say s that a local variable takes precedence
over a global variable with the same name. If you hence declare a local variable, or
a func tion parameter, for that matter, choosing the same name as th at of some global
variable, then you hide that global variable from the code within the func tion body.
The next short example illuminates the whole idea:
var scope = "global";
var f1 = function() { var scope = "local"; return scope; };
var f2 = function() { return scope; };
console.log(scope); //Writes global
console.log(f1()); //Writes local
console.log(f2()); //Writes global
There are two variables named scope in the example. The first one is declared outside
of any of the functions and is hence a glo bal variable. The second one is declared
within the body of the f1() function, which makes it a local variable of that function.
The first call to console.log() takes place outside of any function and can th erefore
only access the global scope variable. The seco nd call to console.log() writes
out wh atever f1 () returns, which is the value of its local scope variable. Namely,
f1() ha s no access to the global s cope variable, which is hidden by the local variable
with the same name. Finally, the thir d c all to console.log() writes out what f2()
returns, which is the value of the global sco pe variable since this is the only variable
accessible within the b ody of f2().
To help you better visualize the situation, here’s a graphical representation of the
scopes of the two scope variables.
global
var scope = "global";
f1
var scope = "local";
f2
The white area indicates the scope of the local scope variable, whereas the scope of
the glo bal scope variable is shaded gray.
Mike: I sh ould probably have asked this before, but are the re any limitations on where
you can declare variables? You a lways declare them a t the beginning of your code or
a f unction body, altho ugh I think I saw them declared elsewhere as well.
10.4. Variable Scope 197