Scope & Closures

Perhaps one of the most fundamental things you’ll need to quickly come to terms with is how scoping of variables really works in JavaScript. It’s not enough to have anecdotal fuzzy beliefs about scope.

The Scope & Closures title starts by debunking the common misconception that JS is an “interpreted language” and therefore not compiled. Nope.

The JS engine compiles your code right before (and sometimes during!) execution. So we use some deeper understanding of the compiler’s approach to our code to understand how it finds and deals with variable and function declarations. Along the way, we see the typical metaphor for JS variable scope management, “Hoisting.”

This critical understanding of “lexical scope” is what we then base our exploration of closure on for the last chapter of the book. Closure is perhaps the single most important concept in all of JS, but if you haven’t first grasped firmly how scope works, closure will likely remain beyond your grasp.

One important application of closure is the module pattern, as we briefly introduced in this book in Chapter 2. The module pattern is perhaps the most prevalent code organization pattern in all of JavaScript; deep understanding of it should be one of your highest priorities.