#JavaScript

Understanding Closures in JavaScript

Understanding Closures in JavaScript

Closures are functions that retain access to variables from their outer scope.

1. Basic Example

function outer() {
  let counter = 0;
  return function inner() {
    counter++;
    return counter;
  }
}
const count = outer();
console.log(count()); // 1

2. Use Cases

  • Data privacy
  • Function factories
  • Maintaining state

Conclusion

Closures are powerful for encapsulation and functional programming in JS.

💬 Comments (1)

js_enthusiast
js_enthusiast

Closures always confused me. This example clears it up!

10/2/2025❤️19