A Function’s Scope Chain
Scope Chaining, Lexical Scope, Block Scope
When an execution context is created, so is its scope chain.
The scope chain is simply the memory space of the function that was called, and the memory space of its outer environment.
A Little More in Depth
If a function is called within a function, it will have a scope chain of its own memory space, its outer environment’s memory space, and the global execution context’s memory space.
Scope chaining is simply the process of the JS Engine scanning the scope chain for the called variable, argument or function.
It starts looking from its inner most environment and scanning out. Ultimately, it will return the value of the the called variable, argument, or function, as soon as it finds it in the scope chain, or it will return a reference error that will say the variable, argument, or function that was called is not defined, which means it does not exist in its scope chain.
Here is a simple example that shows a function using its scope chain.
function writeStuff(){
console.log(greeting);
}var greeting = 'Hello!';writeStuff(); // will print 'Hello!'
To understand why this code worked, you must understand execution contexts and hoisting.
Lexical Scope
Lexical literally means ‘related to words,’ so whenever you see the word lexical understand it means where the code is actually written in the code. What is important about lexical scope is simply understanding that if a function is lexically sitting inside another function, you know that its outer environment when it is called is the function in which it sits.
function writeStuff(){
var greeting = 'Goodbye!';
function writeThis(){
console.log(greeting);
}
}var greeting = 'Hello!';writeStuff(); // will print 'Goodbye!'writeThis(); // will return an error
Block Scope
A function’s block scope is just what is available to it within the function, not in its outer environment.