DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What is a Closure?

A closure is a function that remembers variables from its outer function, even after the outer function has finished executing.

A closure is created when an inner function remembers and accesses variables from its outer scope.

Example:

function outer() {
let name = "Sathish";

function inner() {
    console.log(name);
}

inner();
Enter fullscreen mode Exit fullscreen mode

}

outer();

Output:

Sathish

Explanation:

  1. outer() creates a variable called name.
  2. inner() accesses the name variable from the outer function.
  3. When inner() runs, it prints "Sathish". This demonstrates closure-related scope behavior. Let's see the more important example below, where the inner function is used after the outer function finishes.

Important closure Example:

function outer() {
let count = 0;

return function inner() {
    count++;
    console.log(count);
};
Enter fullscreen mode Exit fullscreen mode

}

let result = outer();

result();
result();
result();

Output:
1
2
3

Why do we use closures?

  • To preserve variables between function calls.
  • To create private variables.
  • To maintain state in JavaScript.
  • To build counters and callbacks.

Top comments (0)