Scope Chain
Overview
Scope determines the accessibility of variables. JavaScript uses 'Lexical Scoping', meaning scope is determined entirely by where the function is physically written in the code.
When a variable is used, the JS engine looks for it in the current scope. If it's not found, it looks in the outer parent scope, and continues looking up the 'chain' all the way to the Global Scope. If it hits the Global Scope and still can't find it, it throws a ReferenceError.
Syntax
const globalVar = "Global";
function outer() {
const outerVar = "Outer";
function inner() {
const innerVar = "Inner";
// inner() can access all 3 variables!
// It looks locally, then up to outer(), then up to Global.
console.log(innerVar, outerVar, globalVar);
}
// console.log(innerVar); // ERROR! Cannot look DOWN the chain.
inner();
}Common Pitfalls
- Accidentally creating global variables by forgetting
const/let. If you writemyVar = 5inside a function, JS looks all the way up the chain, fails to find it, and actually creates a global variable for you (if not in Strict Mode)!
Interview Questions
No. The Scope Chain only works outwards/upwards. Inner scopes have access to outer scopes, but outer scopes cannot look down into inner scopes.
Real-World Example
React components use the scope chain constantly. An onClick handler defined inside a component can access state variables defined at the top of the component because of lexical scoping.
function App() {
const [count, setCount] = useState();
// Accesses 'count' via scope chain
const increment = () => setCount(count + 1);
}Check Your Knowledge
Test your understanding of Scope Chain with these quick questions.