Understanding closures in javascript
I heard the name “JavaScript” in 2009 when I was at grade 8. I was just copy pasting the code by downloading code from some website and pasting. I has no idea that it will be one of my companion later in life. We all know something about JavaScript but for most of the developers the core part of how the Javascript works under the hood is out of this world and I was one of them. So I decided to dive deep into it’s concept.
The Wikipedia defines closures as:
In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment.
The whole idea of closures comes because JavaScript is a lexically scoped language which means variables create their scope when they are defined not when they are executed. Since Javascript functions are first class objects and are treated like variable object you can do anything with then like pass to another function. So when the Javascript engine goes line by line it sets the scope of what variables are accessible to that function.
Now there is another sweet feature in Javascript that you can return a function from another function. This is also because functions are the first class citizen in javascript. When we return a function from another function that we get something amazing called closures. Give me a minute to expalin this through CODE.
// foo is a higher order function which accepts two parameters
// 1. An integer n
// 2. A callback function callbackfunction foo(n){
function callback(){
return n++
}
return callback;
}my_returned_function = foo(10)
console.log(my_returned_function())
//* Prints 11
console.log(my_returned_function())
//* Prints 12
As we can see from above example the function was somehow about to memorize what value it has previously. This may be a surprise for lot of you as once the execution of the function is completed it’s local variables are out of scope(not accessible), but how the hell this happened. The answer to this is something called the [[scope]] property. This property is an hidden property.So take this analogy,when the function callback is returned from foo it automatically gets a backpack that contains the variables which are in it’s scope. Since the variable “n” was available for callback when it defined inside foo, it makes it way to the backpack. This is why when we call the function my_returned_function two time it is able to get that variable and change it accordingly.
Thanks guys for reading this. Since this is my first post in medium, I will be glad if you can give me feedback so that it can improve more.