What is JavaScript Closures and Actual Use of Closures
Most of the developers confuse about closures, what is the use of closures in the real world and In almost interviews of JavaScript closures is a very basic question. Let's Understand Closures —
In Simple words —
In closure There is two functions one is outer and one is inner. Outer function returns inner function.
function outer(a) {
return function(b){
return a+b;
}
}
Call —
let obj = outer(5)
obj(5) => 10
In this returning anonymous function is closure to the outer function.
Why use closures if we can do same thing without closures like that —
function outer(a,b) {
return a+b;
}
Cool! So look in the given example it will clarify all your doubts —
var data = (function () {
var privatefunction = function () {
alert(‘Inside call’);
}return {
publicfunction : function () {
privatefunction();
}
}
})();
here behavior of data is an object and we can not access private function direct by calling — data.privatefunction()
we can just only access data.publicfunction()
So this is a very good example to use closures in a real-world application so basically, we are able to hide some of our methods and make them private.
Thanks, Guys