Now, we'll get into closures, which is apparently a scary topic in JavaScript. However, the basic concept is approachable: a closure is simply a function inside another function with access to the scope chain of its parent function. In this case, it has three scope chains: its own, with variables defined within itself; global, with all the variables in the global scope accessible to it; and the parent function's scope.
Here's an example that we'll dissect:
function someFunc() {
let bar = 1;
function zip() {
alert(bar); // 1
let beep = 2;
function foo() {
alert(bar); // 1
alert(beep); // 2
}
}
}
Which variables are accessible to which functions? Here's a diagram:
Figure 5.5 – Closures
Starting from the bottom up, foo has access to beep and bar, whereas zip has access only to bar. So far, so good, right? Closures are just a way to describe the scope that each nested function has available to it....