DEV Community

Abdul Ahad Abeer
Abdul Ahad Abeer

Posted on • Originally published at abeer.hashnode.dev

What is Closure in JavaScript and How is it Useful?

A closure is a feature in JavaScript where an inner function has access to variables from its outer function, even after the outer function has finished executing. This allows the inner function to remember the environment in which it was created.

How Does a Closure Work?

When a function is created inside another function, it forms a closure. The inner function has access to Its own variables, Variables from the outer function and Global variables.

The key part of a closure is that the inner function retains access to the outer function's variables, even after the outer function has returned.

Example of a Closure:

function outer() {
  let count = 0; // Variable in outer function

  function inner() {
    count++; // Inner function has access to count
    console.log(count);
  }

  return inner;
}

const counter = outer(); // outer function returns inner
counter(); // 1
counter(); // 2
Enter fullscreen mode Exit fullscreen mode

In this example the inner function has access to the count variable from the outer function, even after the outer function has returned. Each time counter() is called, the count value is incremented and its value is remembered between calls because of the closure.

Why are Closures Important?

  • State Persistence: Closures allow functions to keep "state" between different calls, even after the outer function has finished execution.

  • Modularity: Closures make your code more modular, enabling better data encapsulation and reducing reliance on global variables.

  • Functional Programming: Closures are widely used in functional programming, a paradigm in JavaScript.

That’s all what closure is in JavaScript.

Top comments (0)