Java Reference
In-Depth Information
locala(); // invoke the locala function
console.log("a outside function: " + a);
This results in the subsequent console log:
"a inside function: 3"
"a outside function: 1"
In the example, a is defined globally outside the function and is given the value of 1 . This
means it has global scope and is available inside and outside the function. But then a is
defined inside the local function using var . This gives it local scope inside the function
where it has a value of 3 , but it retains the value of 1 outside the function. For all intents
and purposes, the two a variables are different variables.
Here's another example where we define a global variable and then overwrite it from within
the function:
b = 2;
function localb() {
b = 4; // overwrites the global variable
console.log("b inside function: " + b);
localb(); // invoke the localb function
console.log("b outside function: " + b);
Here's the resultant console log:
"b inside function: 4"
"b outside function: 4"
In this example, b is defined globally outside the function and given the value of 2 . Yet b
is not declared using var inside the function, so it still refers to the global variable outside
Search WWH ::

Custom Search