Sobes.tech
Junior

Milleks on vaja kasutada JavaScriptis sulgemist?

sobes.tech AI

Vastus AI-lt

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.
  • Data encapsulation, 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 count variable from the outer function, even after makeCounter has completed.