My FeedDiscussionsHashnode Enterprise
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMSΒ for Enterprise.
Upgrade ✨Learn more
JavaScript Closures

JavaScript Closures

In this blog we are going to understand what closures really are and when and why should we use JavaScript closure.

Sohan Shetty's photo
Sohan Shetty
Β·May 12, 2022Β·

4 min read

So lets get started,

According to MDN docs

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment)

Before getting into closures it is important for us to understand Lexical scope .

Lexical scope defines how variable names are resolved in nested functions .That is if we have a child function within a parent function , the child function has access to the scope of the parent function and has also access to the global scope. Lets try to understand this through an example.

lexicalScope.png

Inside parent x :  1
Inside child x :  1
Inside child y :  2

Note that the childFuction() function has no local variables of its own . However, since inner functions have access to the variables of outer functions, childFunction() can access the variable y declared in the parentFunction() and also the variables defined in the global scope.

Now this does not display closure,

I know its bit confusing , but you will understand soon why its not really displaying closure.

According to w3schools

A closure is a function having access to the parent scope, even after the parent function has closed

Lets try to understand closure through an simple example.

closure_1.png

Running this code has exactly the same effect as the previous example of the parentFunction() function above. What's different (and interesting) is that the displayName() inner function is returned from the outer function *before being executed.*

At first glance you may think that this code will break . In some programming languages, the local variables within a function exist for just the duration of that function's execution . Once the makeFunction finishes executing, you might expect that the name variable would no longer be accessible . However, because the code still works, this is obviously not the case in JavaScript.

The reason is that functions in JavaScript form closures.

A closure is the combination of a function and the lexical environment within which that function was declared.

This environment consists of any local variables that were in-scope at the time the closure was created. In this case makeFunction returns an instance of the function displayName that is created when makeFunction is run.

The instance of displayName maintains a reference to its lexical environment, within which the variable name exists. For this reason , when the function displaySnicker , displayJohn and displayNatasha are invoked , the variable name remains available for use.

Here's what the output of the above code looks like ,

Snicker
John
Natasha

Lets just have a look at one more example to make things bit more clear.

This time lets use an IIFE(Immediately Invoked Function Expression). An IIFE is a JavaScript Function that runs as soon as it is defined.

closure_2.png

Timer for 3s
3 remaining...
2 remaining...
1 remaining...
Times up!!!

In this code the timer gets a function which is returned by an IIFE . Note that the console.log(Timer setted for ${sec}s) is executed only once , that's because the outer function is executed only once and then the inner function ( i.e. stored in timer ) is called to decrement the timer.

One more reason to use closures in JavaScript is to create private variables. Languages such as Java allow you to declare methods as private, meaning that they can be called only by other methods in the same class. JavaScript previously didn't have a native way of declaring private methods, but it was possible to emulate private methods using closures.

Lets see an simple example to understand this.

closure_3.png

Here there is a single lexical environment that is shared by the three functions counter.increment , counter.decrement , and counter.value. Note that here count is acting as an private variable, you can't access it from outside the anonymous function. Instead, you can access it using the three public functions that are returned from the anonymous wrapper. Those three public functions are closures that share the same lexical environment. Thanks to JavaScript's lexical scoping, they each have access to the count variable.

Here's what the output the following code looks like

1
2
1

Summary :

  • Every closure has three scopes: global, local, and block Scope.
  • Closures (that inner function or function returned by another function) have a reference to their lexical environment during the time of their creation.
  • Closures can help you create private data, whether it’s a private method or a private variable.

In other way you can also look at closures like whenever you have a function inside another function, then you may have a closure but it can also be Curried functions. You might be thinking what are they now , well that can be the topic for my next blog πŸ˜‰.

I hope you understood about closures and now you can also explain someone what really closures are. Thanks for reading my blog , I hope it was helpful. Do share it if you find this useful. That's it in this , blog hope to see you in the next blog πŸ‘‹.