JavaScript Closures

Subject: JavaScript

A closure in JavaScript is a feature where an inner function retains access to variables of its outer function even after the outer function has finished executing. Closures enable private variables, persistent state, and advanced function patterns.


What is a Closure?

A closure provides access to:

  • Its own scope (variables declared inside the function)
  • The outer function's variables
  • The global scope (if applicable)

Syntax Example

Explanation:

  • outerFunction creates a local variable outerVariable.
  • innerFunction accesses outerVariable due to closure.
  • Even after outerFunction returns, innerFunction retains access to outerVariable.

Use Case 1: Data Privacy (Private Variables)

Here, count is private and accessible only via the returned function.


Use Case 2: Function Factory

Each generated function remembers the factor used during creation.


Use Case 3: Delayed Execution

Even after delay, the callback accesses the name variable via closure.


Common Mistake: Using var in Loops

Fix using closure:


Key Takeaways

  • Closures allow functions to remember variables from their outer scope.
  • Useful for creating private data and maintaining state.
  • Enable function factories and handling asynchronous code.
  • Be mindful to avoid unintended memory retention causing leaks.
Next : Hoisting