Sobes.tech
Junior

Why is closure used in JavaScript?

sobes.tech AI

Answer from AI

A closure in JavaScript is a function that 'remembers' the environment in which it was created, including access to variables from the outer scope, even if that outer function has already finished execution.

Why is this needed:

  • To preserve state between function calls.
  • Encapsulation of data, creating private variables.
  • Implementation of functions with default parameters or partial application.
  • In React hooks, closures help maintain access to state and props inside functions.

Example:

function makeCounter() {
  let count = 0;
  return function() {
    count += 1;
    return count;
  };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2

Here, the inner function retains access to the variable count from the outer function, even after makeCounter has finished execution.