> Articles > Closure In JavaScript

Closure In JavaScript

A closure in JavaScript is created when a function is available inside another function.

What is Closure in JavaScript?

When a function is available inside another function then closure is created. The inner function will have access to variable and parameters of outer function even after return of outer function. That means we can call the inner function later and it will have access to variables and parameters of outer function. The closure has reference to the variables and parameters of outer function.

Let's see some closure in JavaScript examples-

Example 1

A function is inside another function so closure is created and inside function has access to variable and parameter of outer function.

Closure In JavaScript - Source Code Example 1

Output

Closure In JavaScript - Source Code Example 1 Output

Example 2

Closure will have reference to variable and parameter of outer function, not the actual value.

Closure In JavaScript - Source Code Example 2

Output

Closure In JavaScript - Source Code Example 2 Output

Example 3

For each call to a function a closure is created and value of variable and parameter will be applicable to that closure only.

Closure In JavaScript - Source Code Example 3

Output

Closure In JavaScript - Source Code Example 3 Output


Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books C In Depth, Data Structures Through C In Depth. He has 18+ years experience in industry and worked on architecture and design of multiple products. This article Closure In JavaScript is from his Advanced JavaScript course.