DEV Community

swetha palani
swetha palani

Posted on

Closures in JavaScript

What is a Closure?

A closure in JavaScript is created when a function remembers variables from its outer scope, even after the outer function has finished executing.

In simple words:

  • A closure gives you access to an outer function’s variables from an inner function.
  • JavaScript automatically creates closures when you define a function inside another function.

Example 1: Basic Closure

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

  function inner() {
    console.log("Hello " + name);
  }

  return inner;
}

let greet = outer();
greet();
Enter fullscreen mode Exit fullscreen mode

Output:

Hello JavaScript
Enter fullscreen mode Exit fullscreen mode

Explanation:
Even though outer() has finished, the inner() function still remembers the variable name.

Example 2: Closure with Counter

function counter() {
  let count = 0;

  return function() {
    count++;
    return count;
  };
}

let add = counter();

console.log(add()); // 1
console.log(add()); // 2
console.log(add()); // 3
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
Enter fullscreen mode Exit fullscreen mode

Here, the variable count is private to the function but still accessible through the closure.

Why Use Closures?

  • To remember values even after a function finishes.
  • To create private variables in JavaScript.
  • Useful in event handlers, callbacks, and functional programming.

Conclusion

A closure in JavaScript is a function that remembers variables from its outer scope.
Closures are powerful because they let you keep state, create private variables, and build cleaner code.

Top comments (0)