Lexical Scope with Arrow Functions
You'll learn how arrow functions follow the exact same lexical scoping rules as regular functions when accessing variables.
The Core Idea
Arrow functions don't introduce anything special about lexical scope — they look up variables in the surrounding environment exactly like regular functions do. The scope chain works identically: an arrow function can access variables from its own scope, then its parent scope, and so on up the chain. The key difference we learned earlier (how this works) doesn't apply to regular variable lookups.
Arrow Functions Follow the Same Rules
const outer = 'I am outside';
function regularOuter() {
const middle = 'I am in the middle';
const arrowInner = () => {
const inner = 'I am inside';
console.log(inner); // Own scope
console.log(middle); // Parent scope
console.log(outer); // Global scope
};
arrowInner();
}
regularOuter();
// "I am inside"
// "I am in the middle"
// "I am outside"
The arrow function arrowInner accesses middle from its parent function and outer from the global scope, just like a regular function would.
Think of It This Way
Imagine a filing cabinet where each drawer contains documents and a pointer to the drawer above it. Arrow functions search for variables by checking their own drawer first, then following the pointers upward — exactly the same filing system regular functions use. The scope chain is determined when the code is parsed, not when the arrow function runs.
const multiplier = 10;
const calculate = (x) => {
return (y) => x * y * multiplier;
};
const timesTen = calculate(5);
console.log(timesTen(2)); // 100 (2 * 5 * 10)
Both arrow functions access their lexically-scoped variables correctly through the scope chain.
Key Takeaway: Arrow functions follow identical lexical scoping rules as regular functions — they access variables through the scope chain based on where they're defined, not where they're called.