O'Reilly logo

Functional JavaScript by Michael Fogus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Variable Scope and Closures

This chapter introduces variable scope, an important foundational topic not only to functional programming, but to JavaScript in general. The term “binding” refers to the act of assigning a value to a name in JavaScript via var assignment, function arguments, this passing, and property assignment. This chapter first touches on dynamic scoping, as displayed in JavaScript’s this reference, and proceeds onto function-level scoping and how it works. All of this builds up to a discussion of closures, or functions that capture nearby variable bindings when they are created. The mechanics of closures will be covered, along with their general use cases and some examples.

The term “scope” has various meanings in common use among JavaScript programmers:

  • The value of the this binding

  • The execution context defined by the value of the this binding

  • The “lifetime” of a variable

  • The variable value resolution scheme, or the lexical bindings

For the purposes of this book, I’ll use scope to refer to the generic idea of the variable value resolution scheme. I’ll dig deeper into various types of resolution schemes to cover the full spectrum of scope provided by JavaScript, starting with the most straightforward: global scope.

Global Scope

The extent of a scope refers to the lifetime of a variable (i.e., how long a variable holds a certain value). I’ll start with variables with the longest lifespan—that of the “life” of the program itself—globals.

In JavaScript, the following ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required