Scope Chain & Closures
Master the invisible boundaries of JavaScript. Learn how variables are protected and how functions remember the world they were born in.
Scope & The Scope Chain
Scope determines the visibility of variables. If you declare a variable inside a function, it is 'scoped' to that function and cannot be seen from the outside.
However, inner functions *can* look outward. If a variable isn't found locally, JavaScript looks up the 'Scope Chain' to the parent function, and keeps looking until it hits the global scope.
What is a Closure?
A closure is a feature where an inner function 'remembers' the variables from its outer scope, even after the outer function has finished running.
When a function returns another function, the returned function carries a 'backpack' containing all the variables it needs from its birthplace.
Creating private state
Closures are the secret to creating private data in JavaScript. If you have a createCounter() function that defines a count variable and returns an inner function that increments it...
The outer function finishes, but the inner function still has exclusive access to count in its closure backpack. Nothing else in your entire program can touch that count variable directly!
The Closure Counter
Create a counter factory and watch how the inner function retains access to the private count state across multiple separate executions.
The Closure Counter
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Lexical scope means physical placement in the code dictates variable access.
- Inner functions can look outward (Scope Chain), but outer functions cannot look inward.
- A closure is an inner function that 'remembers' its outer variables even after the outer function finishes.
- Closures are the primary mechanism for achieving data privacy in JavaScript.
Done with this concept?
Mark it complete to track your progress. No login needed.