DEV Community

Mohan Mogi
Mohan Mogi

Posted on

Understanding Closures in JavaScript: A Complete Beginner Guide

closure;
In Javascript,closure is a feature.Closure is an inner function is retains accces to the variables of its outer(enclosing) function,even after that outer function has finished executing.A closure is the combination of a function and the lexical environment in which it was declared.

output:

Explanation:
Step 1:
outerFunction() runs
let count = 0;

Variable count is created.

Memory:

count = 0

Step 2:
innerFunction is created
function innerFunction() {
count++;
console.log("Count:", count);
}

innerFunction uses count from its parent function.

Step 3:
Return inner function
return innerFunction;
const counter = outerFunction();

Now counter stores innerFunction.

Normally outerFunction() would finish and remove its variables from memory.

But because innerFunction still needs count, JavaScript keeps count alive.

This is called Closure.

Step 4:
First call
counter();

Runs:

count++;

Before:

count = 0

After:

count = 1

Output:

Count: 1

flow view:
outerFunction()
|
count = 0
|
return innerFunction
|
counter()
|
count = 1

counter()
|
count = 2

counter()
|
count = 3

counter()
|
count = 4

Top comments (0)