Let's Understand Closures!
JavaScript is one of the most popular programming languages today.
It runs in the browser, on server, it’s on mobile devices , on desktops etc. It is used almost everywhere which makes us to understand its concepts clearly.
So, we need to understand the fundamentals of Javascript in depth to learn the language well.
Here, we will discuss about one of its fundamental concept that is -CLOSURES.
What's a Closure?
Closure can be understood as combination of functions which are bind together with reference to its lexical environment(surrounding).
Or in simple words, you can understand it as “ function inside a function that remembers the stuff around them.”
All functions in JavaScript are closures.
In JavaScript, closures are created every time a function is created, at function creation time. To use a closure, simply define a function inside another function and expose it.
This is an example of closure:
let name = ”John”;
function sayHi(){
alert(“hi ”+ name)
}
name = “Pete”;
sayHi();
When a code wants to access a variable it is first searched for the inner lexical environment,then in outer one then in other and so on.
A function uses the most recent values.
Old variables are not saved anywhere.When a function wants them it takes the current value from its own.
The execution of the above code : 1.The global environment has name: “John” 2.At line 5, the global variable is changed , now it has a name: “Pete” 3.Function sayHi() is executed and takes the value of variable name from its inner lexical environment. i.e “Pete”
Whenever a function is called, lexical environment is created to hold variable . It stores two things :
- Environment record with local a variable.
- Outer lexical reference.
We can say that closures are function that remembers its outer variable and can access them.
Why we use closure?
Closures are used in Javascript to implement encapsulation i.e data hiding by maintaining a lexical scope and accessing to it by way of a function returning value.
Closures are frequently used in Javascript for object data privacy,in event handlers and call back functions.
Conclusion
I would like to conclude it the way I have read it somewhere " The way I will always remember closures is through the backpack analogy. When a function gets created and returned from another function, it carries a backpack with it. And the backpack contains all the variables that were in scope when the function was declared. "
I hope that this blog clears the concept of what closures are. I personally learned it from javascript.info So if you need further understanding of the topic then do visit the link provided.