7 Functions for the master: closures and scopes
This chapter covers
- Exploring how closures work
- How variables are scoped
- When hoisting occurs
Closely tied to the functions we learned about in previous chapters, closures are a defining feature of JavaScript. Although many JavaScript developers write code without understanding exactly how closures work, their use is essential to many common JavaScript patterns. For example, any tasks involving callbacks, such as event handling or animations, would be significantly more complex without closures.
Closures are a side effect of how scopes work in JavaScript. For that reason, this chapter will explore the scoping rules of JavaScript. Understanding scopes will allow you to take full advantage of closures. Let’s jump right in!
7.1 Understanding closures
A closure allows a function to access and manipulate variables that are external to that function. Closures allow a function to access all the variables, as well as other functions, that are in scope when the function itself is defined.
NOTE
A scope refers to the visibility of identifiers in certain parts of a program. A scope is a part of the program in which a certain name is bound to a certain variable.