Sobes.tech
Junior

What is a closure in JavaScript?

sobes.tech AI

Answer from AI

Closure is a function that remembers the environment in which it was created, even after that environment has finished executing. It retains access to variables from the outer (enclosing) function.

This is possible because when a function is created in JavaScript, a "lexical environment" is also created, which contains all the variables and functions accessible at that moment. Even when the outer function finishes, this lexical environment is preserved in memory if there is a reference to it from within the created function.

function outerFunction(outerVariable) {
  return function innerFunction(innerVariable) {
    // innerFunction has access to outerVariable from the closure
    console.log('Outer variable:', outerVariable);
    console.log('Inner variable:', innerVariable);
  };
}

const newFunction = outerFunction('Hello from outside');

newFunction('Hello from inside'); // Outer variable: Hello from outside, Inner variable: Hello from inside

Main applications:

  • State preservation: You can create functions that remember certain values between calls.
  • Emulation of private variables: JavaScript does not have built-in private variables in the classical sense, but closures allow this by hiding variables inside the scope of the outer function.
  • Currying and partial application: Creating new functions with preset arguments.
// Example of a private variable
function createCounter() {
  let count = 0; // This is a "private" variable thanks to closure

  return {
    increment: function() {
      count++;
      console.log(count);
    },
    getCount: function() {
      return count;
    }
  };
}

const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
console.log(counter.getCount()); // 2
// console.log(counter.count); // undefined - direct access to count is impossible
What is a closure in JavaScript? — Node.js - sobes.tech