Scoping in JavaScript
You might be wondering how your program’s variables are organized and scoped.
The scope is a space in which you can declare your variable. There are three types of scope in JavaScript :
1.Global Scope: refers to space outside of any function or block. Variables declared in the global scope are accessible everywhere.
2. Function Scope: Variables that are declared inside the function are not accessible outside of the function.
3. Block Scope (ES6): Variables are accessible only inside the block ( if block for instance) . This only applies to let and const variables NOT var. Variables declared with var end up in the closest function scope. Functions are also considered as block scoped.
Scope chain: Every scope always has access to all the variables from all its outer scopes.
Variable lookup: Looking up the variable in the scope chain to find a variable that is not in the current scope.
Please note that :
- every scope has access to its parent scope. The scope has access to variables from all outer scopes.
- The scope chain has nothing to do with the order in which functions were called.
- The scope chain is a one-way street. the scope will never have access to the variables of an inner scope