Closures JavaScript
The documentation states that closure is just a combination of a function bundled together, with references to its surrounding states(the lexical environment). In short, if we are writing some function, inside another function (which is perfectly fine here), and if the outer function contains some variables, the inner function has access to all those variables, even if that function has finished execution. So, a closure gives us access to an outer function’s scope from an inner function.
As we take an example, you would be able to get the basic thing about the closures. Have a look at the below basic program, and let’s try to get to a solution –
As you can see, we have created a variable myName, where we are storing a string. Now, inside the function say my name, we can use that variable directly as well. If we try to run the above program, the output we are going to get on the console is the same string. Have a look at the output –
As you can see, we could use the variable directly in the function. Now, let’s try to create another function inside this function. Have a look at the below program –
As you can see, we have created a function just for fun, and inside that, we have created another function seriously(this is seriously a function name). There is a variable, which is made inside the function just for fun and not inside seriously. But still, the function seriously has an access to the variable myName.
Now, remember from the previous discussion? The inner function has access to the variables from the outside function’s scope. The same thing is happening here. Well, now you would say that ok… maybe because the function just for fun is still executing, so the inner function is able to access the variables from its scope. For that, let me tell you that you can return some function, from another function, and use it later. Let’s do this now.
As you can see, we created a variable call function, to hold the inner function. Now, since we are returning the function, we are running it after the function just for fun has finished execution(because the return statement is the last thing in the function since the statements after the return statement are unreachable). Now, you might think that ok.. this time, the variable is not available, since the function has finished the execution, and so, the context now may not be available. However, this is not true. Have a look at the output now –
What??? we are still able to use the variable from the outer function scope? Well, this is the power of closures. This is a pretty interesting, useful, and important feature in JavaScript. I hope that you have got the basics of what closures are. Also, you can explore the concept in more depth.