Back to stories
<Frontend/>
Premium

JavaScript Closures and Scope: A Deep Dive for Senior Engineers

Share by

JavaScript Closures and Scope: A Deep Dive for Senior Engineers

Closures and scope are at the heart of JavaScript. A closure is a function that "remembers" the lexical environment in which it was created—even after that outer function has returned. Lexical scope means that the scope of a variable is determined by where the code is written, not where it runs. This post explains how the engine implements these concepts, common patterns, and pitfalls senior engineers need to avoid.


Lexical scope and the scope chain

Lexical scope means that when the parser sees a function, it ties that function to the scope where it was defined. At runtime, when you access a variable, the engine looks in the current scope, then in the parent scope, then the grandparent—the scope chain—until it finds the variable or reaches the global scope.