Understanding closures in Javascript - Javascript weekly

In this article, we will see what closure is and why do we need something like closure, Understanding closures in Javascript - Javascript weekly

Previous Article : https://cloudnweb.dev/2019/06/understanding-generators-in-javascript-javascript-weekly/

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.


Problem Statement

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

  1. Problem Statement
1let name = "Ganesh"
3function getMyName() {
4 console.log("Name is " + name)
7name = "Mani"
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"
4 return function() {
5 console.log(name)
6 }
9let name = "Mani"
11// create a function
12let myname = getMyName()
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


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"
4 this.lastName = "Robert"
7User.prototype.getFirstName = function getFirstName() {
8 console.log(this.firstname)
11User.prototype.getLastname = function getLastname() {
12 console.log(this.lastName)
15User.prototype.showFullName = function showFullName() {
16 console.log(this.firstname + " " + this.lastName)
19module.exports = User

we are creating a function called user and add the function getFirstName, getLastName and showFullName for the particular user function and access the function variable with this keyword.

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

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

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"
4 let lastName = "Smith"
6 return {
7 getFirstName: function() {
8 console.log(firstName)
9 },
11 getLastName: function() {
12 console.log(lastName)
13 },
15 showFullName: function() {
16 console.log(firstName + " " + lastName)
17 },
18 }
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
3let userClosure = require("./user_closure")
5let closureresult = userClosure()

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 this keyword.

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
4 return function() {
5 counter++
6 return counter
7 }
10let increment = doIncrement()
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 the concept out of it.

Reference :


we will see some other features of javascript in upcoming articles.

Until then, Happy Coding :-)

To Read More

Kubernetes for Nodejs developers

Do you keep hearing the word kubernetes in the tech community and you couldn't u...

TypeScript Interfaces vs Types

In this article, we will see what are interfaces and types and the difference be...

How to find project ideas to practi...

Ever wondered what how to get a real world experience on web development while w...

Building a Production-grade Nodejs,...

This article is the first part of building a production grade nodejs,graphql and...

Modern React Redux Tutorials with R...

This tutorial explain how you can build an application using modern react redux ...

Building a Piano with React Hooks

In this article, we will see how to build a piano with react hooks. Building a P...

TypeScript Basics - The Definitive ...

In this article, we will learn some basics of typescript which helps you to deve...

Here's why podman is more secured t...

In this article we will see about podman and why it is more secured way to run c...

What is gRPC ? How to implement gRP...

Everyone talks about gRPC. Have you ever wonder how it works or how to implement...