Closure in JS

Naseeb Shah
CodeX
Published in
3 min readJun 18, 2022

The closure is a concept in JavaScript. This is a widely confusing concept that is asked in common interviews with web developers.
We will discuss this concept in this blog.

Before moving on, we will get acquainted with the variable scope in JavaScript.

JS has three types of scope.

Global Scope:- A variable declared outside the function called the global scope variable. You can access these variables anywhere in the javascript program.

Local Scope:- A variable declared within function and you can not access these variables outside function.

If a variable declared with “let or var” is mutable. You can change the value of this variable at any time. And the other hand, “const” declared variables are unmutable in nature. You cannot change this variable value.

Closure:- In JavaScript ,a closure in a function that references variables in the outer scope form its inner scope. The closure preserves the outer scope its inner scope.

Simply, a closure can be defined as JS features that include two functions nested or return types, the child function having access to the parent function variable. You can say that, to provide a function global scope variable, another function is created. : — — S&D Shah

Let us see how closure works with the help of an example:-

The above code an example of a simple closure function.

The above code is an example of a simple closure function. In this code there were two functions named child and parent. The child function accesses the parent function variable “ g__var” inside the child function. As you can see, the parent function provides the accessibility of the child variable to the child function.

What is the practical use for closure in JavaScript?

  1. Using private variables and methods
  2. Maintaining state between each function call:
Using private variables and methods

The above code is closure with function private variables and methods. There are main function is setrentvalue and when we are passing arguments in setrentvalue, then set the initial value of the rent variable. And its make global type scope for methods . The method uses this variable like as globally variable and we can perform a variety operations like increment rent and decrement rent etc.

Maintaining state between function calls

The above code main condition between function calls. As you can see when we make the first call at that time multivalue = 9 and after calling this for the next call multi the initial value is equal to the starting value of multi 9 * 2 = 18. 18. Value multiples like previous equal multiple value.

………………………………… Thanks ………………………………

--

--