DEV Community

Abdul Ahad Abeer
Abdul Ahad Abeer

Posted on • Originally published at abeer.hashnode.dev

1

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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay