Samer Buna
2 min readFeb 19, 2017

--

Thanks for pointing those out. The article is focused on the high-level understanding of closures but there is a lot more to it than that. I personally think the word scope is overused, especially when we start mixing lexical environments and execution contexts under the term.

Closures are a side effect of the scoping rules in JavaScript. They allow a function to access variables that are in scope when the function is defined. A scope (as associated by most) is just a record of what variables are bound to what values. Every function creates that record when it’s executed, including parent functions and even the global function (the running program). This is just an ok simplification. To be more accurate, when a function is executed, it gets a lexical environment and an execution context (the temporary scope). The global program also gets an execution context, but that one sticks around until we exit the program. Please note that this execution context is not the same as the function context (which you can access with this)

Because of the single-thread model, when you execute a new function, the current execution context has to be paused, a new execution context is created, used, and then discarded, and the previous “caller” execution context will resume after that. That’s what the call stack is for.

The lexical environment is used to keep track of references or identifiers, both local and in outer parent lexical environments (AKA scope chain). Because functions are first-class objects in JS, their lexical environments can be stored internally and passed around with the object (that’s why the position at which the function is defined is not related to the position at which the function is called, and that’s where closures play their role)

To truly master these concepts, I encourage you to read beyond one book or one author.

--

--

Samer Buna

Author for Pluralsight, O'Reilly, Manning, and LinkedIn Learning. Curator of jsComplete.com