When working with closures you'll often hear the words "capture", "wrap", or "enclose". The entire idea behind a closure is to take a variable outside of the function and use that variable inside the function. A closure enables patterns for passing around functions that can manage buffers, caches, and values that can travel with the function.
A Community Resource means that it’s free to access for all. The instructor of this lesson requested it to be open to the public.
John Lindquist: Closure() is a function that accesses stuff not defined inside of it. If I defined a name up here of John and then console.logged out a name in here and called the closure, that would log out John. If I reassigned name to Mindy and then called the closure again, it logs out John then Mindy.
If I set this to i and set this at , and then I logged out i++, every time I called the closure, we'll call it three times, you'll see, I'll zoom in, , 1, and 2. The huge difference here is if I was defined inside the closure and I hit Save, you'd see , , and because this is inside of the scope of this function and is recreated each time the function is called.
It's the ability of functions to capture anything outside of the function and use that value each time the function is called, that make closure special.
Isn't this just accessing a global variable? Don't we need an enclosing function to create a closure?
function outer(i) {
let closureVar = '1';
return function inner() {
console.log(closureVar + i);
}
}
outer(1)();
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).
So this is still a valid example of a closure since it is a function that is accessing the state of its surrounding environment.