I understand how it works (the disparities between local and global functions), but I don’t quite get the rationale behind hiding the global variables in a functions while a “local” variable is not yet defined or initialized.
var scope = "global";
function checkscope() {
console.log(scope);
}
//this returns >> undefined
I’m reading "Javascript: The Definitive Guide (6th edition)" and I’m talking about chapter 3.10 here. (page 54 to be exact).
2 pages later, at page 56 the book says:
“In a non-nested function, the scope chain consists of two objects. The first is the object that defines the functions parameters and local variables, and the second one is the global object.”
Wouldn’t that mean that global variables, “properties” of the global object are in the scope chain of a non-nested function? Doesn’t that contradict what was said 2 pages earlier?
I’m not the best at verbalizing myself, so I hope you guys understand, furthermore, English is not my native language so I apologize if this is just a misunderstanding of the meaning of the text on my part.
According to the comments, the code in question is:
var scope = "global";
function checkscope() {
console.log(scope);
var scope;
console.log(scope);
}
This will log undefined
twice, as var
declarations (as well as function declarations) are hoisted up to the top of the current scope. The script above is interpreted as:
var scope = "global";
function checkscope() {
var scope; //declaration hoisted up to top of scope
console.log(scope);
console.log(scope);
}
As checkscope
has a local scope
variable, the local scope
variable shadows the outer scope's scope
variable.
The local scope
variable has no value assigned to it, which is equivalent to JavaScript's native undefined
value.
Side-note: if the outer scope in question is the global one, inside a browser environment, you can still access the global scope
variable by referencing the global object (window
):
var scope = "global";
function checkscope() {
var scope; //declaration hoisted up to top of scope
console.log(scope); //undefined
console.log(window.scope); //"global"
}
As you can see, variables declared in the global scope become properties of the window
object.
This trick is not very useful when the outer scope is non-global, the scope
variable will remain shadowed unless you rename it. There is no standardized way to access shadowed properties (variables/functions) of parent scopes' execution contexts as far as I know.