Eugene fishing

First Dive Into JavaScript Closures

A JavaScript closure is formed when you define a function within a function. The inner function will remember the variables of the outer function, which encloses it, even after the outer function has finished executing.


Here's an example:

function outerFunction() {
  const outerFunctionVariable = `the outer function's data`;

  const innerFunction = function() {
      console.log(`I remember ${outerFunctionVariable}!`);
  }

  return innerFunction;
}

const closureFunction = outerFunction();
closureFunction();

Output:

I remember the outer function's data!

As you can see above, outerFunction was invoked, and returned innerFunction, which was stored in closureFunction.

Then, closureFunction was invoked, which referenced innerFunction, and printed the data from outerFunction.

innerFunction remembered the variable of the outerFunction even after outerFunction was finished executing.

Apparently, there are many use cases for JavaScript closures, which we'll cover in the next webLog.

Some use cases are:

  • Data Encapsulation and Privacy
  • Function Factories
  • Callback Functions
  • Event Handlers
  • Memoization
  • Partial Application and Currying
  • Module Pattern
  • Timeouts and Intervals
  • Asynchronous Programming
  • Emulating Private Methods
  • Managing State in Iterators
  • Event Handling in React or UI Frameworks
  • Creating Memoized Functions
  • Handling Asynchronous Flows with Promises
  • Singleton Pattern
  • Dynamic Function Generation
  • Custom Callback and Filters
  • Debouncing and Throttling

See you next time!