Skip to main content

Understanding closures in Javascript -

What is Closure?

In simple terms, Closure is nothing but a function which is defined inside another function. the closure has access to all the local variables, outside function variables and global variables.

closure

Problem Statement

To understand this in a better way, consider the following result of code.

  1. Problem Statement
1let name = "Ganesh"
2
3function getMyName() {
4 console.log("Name is " + name)
5}
6
7name = "Mani"
8
9getMyName() //what will be the output here?

This kind of scenario is common in web development(front-end as well as backend). we will define a function and call the function later some point of time.

2. Problem Statement

1function getMyName() {
2 let name = "Ganesh"
3
4 return function() {
5 console.log(name)
6 }
7}
8
9let name = "Mani"
10
11// create a function
12let myname = getMyName()
13
14// call it
15myname() // What will it show?

To understand this concept, first, we need to understand the concept of Lexical Environment

Lexical Environment

Lexical Environment is nothing but maintaining the state of the particular function and its outer environment state, variables.

lexical env

Every inner function will have a local variable, inner function can also access the parent function variable and global variable.

Maintaining the scope of the particular function is nothing but a Lexical Environment.

Coming back to Problem Statements...

Now, if we come back to the problem statements, the problem statement #1 would return the value as "Mani"

Because ,The value gets updated since we have defined it as Global Variable.

Now, in Problem statement #2, we have defined a function called getMyName(). inside the function, we have defined a variable called name which is nothing but a parent function variable.

we are returning a function from the getMyName() function.

Now, if we define the same variable called name in the global context and execute the getMyName().

it won't change the value of it. because getMyName() returning a function which is nothing but a Closure will hold the variable state and value for the particular environment

https://output.jsbin.com/qikuginowe

javascript first look inside the inner function, then it will look in the parent function. finally, it will go look in the global variables.

Closure - Practical Implementation

Using Closure instead of objects

If you are familiar with OOPS concepts, you will know that concept of "this", which will refer the context of the class

Let's try to write a function using OO concept and then we will see how we can rewrite that with Closures.

1function User() {
2 this.firstname = "John"
3
4 this.lastName = "Robert"
5}
6
7User.prototype.getFirstName = function getFirstName() {
8 console.log(this.firstname)
9}
10
11User.prototype.getLastname = function getLastname() {
12 console.log(this.lastName)
13}
14
15User.prototype.showFullName = function showFullName() {
16 console.log(this.firstname + " " + this.lastName)
17}
18
19module.exports = User

we are creating a function called user and add the function getFirstNamegetLastName and showFullName for the particular user function and access the function variable with thiskeyword.

To call this particular function we need to create an new instance of it and call the particular function

1let User = require("./user")
2
3let data = new User()
4data.showFullName()

it will show me something like "John Robert"

Now, let's see how we can rewrite this with Closures

1function User() {
2 let firstName = "Will"
3
4 let lastName = "Smith"
5
6 return {
7 getFirstName: function() {
8 console.log(firstName)
9 },
10
11 getLastName: function() {
12 console.log(lastName)
13 },
14
15 showFullName: function() {
16 console.log(firstName + " " + lastName)
17 },
18 }
19}
20
21module.exports = User

we are defining a user function like we did before, then instead of binding the function. we are returning those function from the parent function user.

Note : return functions are nothing but closures.

Now, if i want to call this function , we have to do something like

1//using Closure in Javascript
2
3let userClosure = require("./user_closure")
4
5let closureresult = userClosure()
6
7closureresult.showFullName()

it will return "Will Smith" as output.

This is one of the real-time use cases where can try to implement Closures instead of going with thiskeyword.

Quiz :

Try to solve this problem and comment your result in this post and explain me how it works.

1function doIncrement() {
2 let counter = 0
3
4 return function() {
5 counter++
6 return counter
7 }
8}
9
10let increment = doIncrement()
11
12console.log(increment())
13console.log(increment())
14console.log(increment())
15//What is the result ?

That's it for this week. try to implement this in a real time usecases, so that you can grab 

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...