A ride to closure

Abhishek Saxena
2 min readJun 21, 2020

--

Hey!!!!
Learning JS & every time a thing comes Closure, Ahhhhh i know listening closer is easy and enjoyable but learning it , it is a bit boring & also bit sleepy, But i just want to say it is very IMPORTANT!!!!!. So just start the journey of closure .

So Let’s start with a very Basic Example…Wait waitttt!!!!! 😮
First lets have some theory part 👹—

Closure is a property(Still confused😨…) in JS which enables us to use parent scope variables after the execution of parent is over!!!! 😜.

Wait What……This actually confused me 😢…..

In simple language…In nested function you can use the parent variables in child function and return the computed value from both.

Still not clear ?😥
Lets look a example🤞

function addFunction(x){
return function(y) {
return x + y;
}}
let a = addFunction(5)(10); // result will be 15

Ok Lets Explain this!!!

Firstly we created a function (not using ES6, but i prefer it) addFunction
which is returning a new function(😮)……..which returns finally x + y;
But Let’s see the function calling .

Here we declared a variable a (very bad in choosing name🥺) which calls the addFunction twice (don’t confuse with twice function calling) in the function it will return something like this 👐.

dummy = addFunction(5);// Above line will return something like this.
dummy = ƒ(y) {
return x + y;
}

Here we used dummy to see the first function calling, so when we call the add function with parameter 5 it returns a function like above🤷‍♀.

Now this function is used to call the addFunction again with parameter 10😋

Which still holds the value of x in the scope(that’s the power of closure)

Now when we call the function it will return something like this.

var sum = dummy(10);
console.log(sum) // 15

Thank you for reading 🙌

Clap! if this was useful for you 👋

--

--

Abhishek Saxena
Abhishek Saxena

Written by Abhishek Saxena

Working as a full time Front-End developer & also searching web for some cool stuff.

No responses yet