Back to blog

So what is closure in Javascript?

·2 min read·
JavascriptEngineering Concepts

In JavaScript, closures are an important concept that allows functions to retain access to variables from their outer (enclosing) scope even after the outer function has finished executing. This means that a function can "remember" and access variables from its parent scope, even when it is invoked elsewhere.

Here's an example to illustrate how closures work:

function outerFunction() {
  var outerVariable = 'I am from the outer function';
 
  function innerFunction() {
    console.log(outerVariable);
  }
 
  return innerFunction;
}
 
var closure = outerFunction(); // Assign the inner function to a variable
 
closure(); // Invoke the inner function

In this example, we have an outerFunction that declares a variable called outerVariable and defines an innerFunction inside it. The innerFunction has access to the outerVariable due to closure.

When we invoke outerFunction and assign its return value to the variable closure, we essentially create a closure. The closure variable now holds a reference to the innerFunction, along with its surrounding scope.

Later, when we invoke closure(), it still has access to the outerVariable from its parent scope, even though the outerFunction has already finished executing. The output will be 'I am from the outer function’, demonstrating that the inner function has retained access to the variable through closure.

Closures are powerful because they allow functions to maintain access to variables that are no longer in scope. They are commonly used in scenarios like creating private variables, implementing data encapsulation, and creating functions with persistent state.

Enjoyed this article?

Get weekly insights on software development, architecture patterns, and industry best practices.