Chapter 5. Functions for the master: closures and scopes


This chapter covers

  • Using closures to simplify development
  • Tracking the execution of JavaScript programs with execution contexts
  • Tracking variable scopes with lexical environments
  • Understanding types of variables
  • Exploring how closures work

Closely tied to the functions we learned about in previous chapters, closures are a defining feature of JavaScript. Although scores of JavaScript developers can write code without understanding the benefits of closures, their use can not only help us reduce the amount and complexity of code needed to add advanced features, but also enable us to do things that otherwise wouldn’t be possible, or would be too complex to be feasible. For example, any tasks involving callbacks, such as event handling or animations, would be significantly more complex without closures. Others, such as providing support for private object variables, would be outright impossible. The landscape of the language and the way we write our code is forever shaped by the inclusion of closures.

Traditionally, closures have been a feature of purely functional programming languages. Seeing them cross over into mainstream development is encouraging. It’s common to find closures permeating JavaScript libraries, along with other advanced code bases, because of their ability to drastically simplify complex operations.

Do you know?

5.1. Understanding closures

5.2. Putting closures to work

5.3. Tracking code execution with execution contexts

5.4. Keeping track of identifiers with lexical environments

5.5. Understanding types of JavaScript variables

5.6. Exploring how closures work

5.7. Summary

5.8. Exercises