DEV Community

loading...
Cover image for Master Closures in Javascript.

Master Closures in Javascript.

gautham495 profile image Gautham Vijayan ・2 min read

In this tutorial lets learn about Closures in Javascript.

This article will help you get over the technical jargon of the term closure and will enable you to explain what a closure is to anyone.

In Simple words,

A function within a function , can use the variables of the parent function.

If you have been using javascript higher order functions like map, reduce they are what closures are.

First lets see an example of closures in form of an user defined function.

function closurefunction() {

var number = 1;

function innerfunction(){

alert(number);

} 
innerfunction()
}
closurefunction()
Enter fullscreen mode Exit fullscreen mode

Now when we call closurefunction, the innerfunction is returned.

The inner function here uses the parent closurefunction's 'number' variable.

In programming, local variable of one function can not be used in another function.

But when we use a function within a function, we can access the outer function's variables inside the inner function. This is called closure in programming.

Now an example with a higher order funtion called map,

const array1 = [1,2,3]

const array2 = array1.map(function(el){

return el*2;

}
Enter fullscreen mode Exit fullscreen mode

In the above example, array2 takes map has a function, and map function returns another function which uses the parent 'map' function's data and returns it.

The ES6 form of above code,

const array1 = [1,2,3]

const array2 = array1.map(el => return el*2 )

Enter fullscreen mode Exit fullscreen mode

Summary:

A function which is returned inside another function can use the outer function's variables.

My Personal Experience:

I have been using Higher order functions like map, filter for a long time without knowing that they are called closures. If you did the same comment below!

Thank you for reading!

If you like this article, Unicorn this one! Heart/Like this one and save it for reading it later.

My Other Articles:

Discussion (0)

pic
Editor guide