What is JavaScript Closures and Actual Use of Closures

Shivam Gupta
1 min readSep 26, 2018

--

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()

Benefit of closures

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

--

--

Shivam Gupta
Shivam Gupta

Written by Shivam Gupta

Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK...Love to write cool stuff

Responses (1)