Understanding ‘Closure’ in JavaScript

Pluto
1 min readApr 11, 2021

--

Today I learned about ‘closure’ in JavaScript. To make myself understand ‘closure’ deeply, I will write about it as much as possible.

What is ‘closure’ in JavaScript?

‘Closure’ is the property that makes functions pass values from outer functions to inner functions. Usually, the variable which is declared in the local scope is only available in that certain scope. However, the function defined in the closure remembers the environment in which was created and can use the variables which are declared only in the parent function.
Here is an example:

const parentFunction = () => {
let num = 5;
const childFunction = () => {
console.log(num);
};
return childFunction();
};
parentFunction(); // 5

Even though childFunction does not have any variable declared inside, it can use num variable which is declared inside parentFunction.

Another example is below:

const request = (id) => {
let status = true;
return {
checkId: () => {
if (id && status) {
return true;
} else {
return false;
}
}
};
};
const user1 = request('asdf');
console.log(user1.checkId()); //true
const user2 = request();
console.log(user2.checkId()); //false

It gives the closure function ‘checkId’ exclusive access to the status variable while making it impossible to access it from the outside.

Why it is important?

One of the reasons why ‘closure’ is important is following:

  1. We can protect our code by not using many global variables, and make a private reference to a variable in the outer scope (like 2nd example).

--

--

Pluto

Studying at Codechrysalis. Marketing researcher before.