Transcript from the "Closure" Lesson
[00:00:19] Keep in mind when we talked about higher order functions, we said that functions can return other functions as outputs just like they can take in other functions as inputs like map and filter and reduced it. Now here's the other thing, within the body of a function you can define another function.
[00:00:44] And because the body of a function has its own scope, its own notion of the values of variables. When you define an inner function, that inner function has access to the outer function scope. It has access to whatever values that outer function is working with. So if you define a function within another function, when you return out that inner function, an interesting thing happens.
[00:01:17] Which is that you have the possibility for that inner function once it's returned to remember values from the scope in which it was defined even if those are not being passed in directly to the function. [SOUND] What does that even mean? So that's the conceptual. Let's take a look at what that looks like.
[00:01:45] Here is an example of a really simple and perhaps not the most useful, but kind of cool little function called makeAdjectifier which takes in an adjective. This function is gonna define, its defining here another function which takes in a noun. And then because it has access to this scope of this makeAdjectifier function, it's going to return a string that uses both the adjective and the noun.
[00:02:22] So what happens when I call makeAdjectifier with an adjective? If I make a new function called coolify, coolify is what I'm gonna name the function returned by makeAdjectifier when I call it on cool. Now coolify is a function. Remember, this function returns a function. coolify is now something that I can apply to a noun like workshop and get out a string cool workshop.
[00:02:52] I can apply it to a different noun drink and get out a string cool drink. And what this means is that now I can call coolify on whatever nouns I want and it will always remember that the adjective it's supposed to add is cool not rad, awesome, or whatever else.
[00:04:06] But in a closure, we have kind of a loophole for that. We have sort of a way to remember something that is not an explicit argument to the function that nevertheless is useful for its computation without resorting to side effects for example, reading a global adjective variable. So this becomes a really useful tool in functional programming, which is what we're gonna dig into in this section's exercise.