Java Reference
In-Depth Information
the function. This means that
b
is the same variable both inside and outside the function
and the value of
b
is overwritten globally to be
4
.
Here's another example that creates a global variable from within a function that is then
still accessible from outside of function:
function localc() {
c = 5; // creates a new global variable
console.log("c inside function: " + c);
}
localc(); // invoke the localc function
console.log("c outside function: " + c);
This results in the following console log:
"c inside function: 5"
"c outside function: 5"
In the example,
c
is only defined inside the function, but because this is done without using
var
, it has global scope and is also available outside the function.
Here's another function that creates a local variable inside the function that is not accessible
outside the function:
function locald() {
var d = 6; // creates a new local variable
console.log("d inside function: " + d);
}
locald(); // invoke the locald function
console.log("d outside function: " + d);
Here's the console log result:
