DEV Community

Arokiya Kithiyon
Arokiya Kithiyon

Posted on

Closures in Javascript

In JavaScript, a closure is the combination of a function and the lexical environment within which that function was declared. This means that an inner function "remembers" and can access the variables and arguments of its outer (enclosing) function, even after the outer function has finished executing and its execution context has been removed from the call stack.

Another way to think about it — and likely a picture you won’t forget — is to think of closures as a pregnant woman and her unborn baby. Once the baby is born, it still has access to its mom’s DNA even though it is no longer inside the womb. Similarly, a nested function in a closure still has access to its lexical scope, or environment, even after the parent function has finished executing.

Key characteristics of closures:

Lexical Scoping:
JavaScript uses lexical scoping, meaning that the scope of a variable is determined by where it is written in the code, not where it is called. A closure captures this lexical environment.

Data Privacy:
Closures allow for the creation of private variables and methods, as the inner function can access variables from its outer scope, while those variables are not directly accessible from the global scope. This is a powerful mechanism for data encapsulation.

Persistence of State:
Even after the outer function has returned, the inner function retains access to the outer function's variables, allowing the state of those variables to persist across multiple calls to the inner function.

function createCounter() {
  let count = 0; // This variable is part of the lexical environment

  return function() { // This is the inner function (the closure)
    count++;
    return count;
  };
}

const counter1 = createCounter();
console.log(counter1()); // Output: 1
console.log(counter1()); // Output: 2

const counter2 = createCounter(); // Creates a new closure with its own 'count'
console.log(counter2()); // Output: 1
Enter fullscreen mode Exit fullscreen mode

In this example, createCounter returns an anonymous inner function. This inner function forms a closure over the count variable declared in createCounter. Each time counter1() is called, it increments its own count variable, which persists between calls. counter2 creates a separate closure with its own independent count.

Top comments (0)