Scope & Closures
30 min read
ScopeClosuresGlobal ScopeBlock ScopeFunction ScopeLexical Environment
Understanding Memory and Variable Access
Scope determines where variables are accessible. Closures are functions that "remember" the scope they were created in, even after that scope has closed.
Types of Scope
- Global Scope — Accessible everywhere (avoid polluting!)
- Function Scope — Variables declared with
var - Block Scope — Variables declared with
letandconst
Closures
A closure is created when a function accesses variables from its outer (enclosing) scope. This is the foundation of data privacy, memoization, and event handlers in JavaScript.