Sobes.tech
Junior — Middle

What is the role of closures in JavaScript and what are they used for?

sobes.tech AI

Answer from AI

Closures in JavaScript are functions that "remember" the environment in which they were created, including access to variables from an outer function even after it has finished.

Role of closures:

  • Allow creating private variables and methods, encapsulating data.
  • Used to create functions with preserved state.
  • Help avoid polluting the global scope.
  • Used in functional programming to create functions with partially applied arguments.

Example:

function makeCounter() {
  let count = 0; // private variable
  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, creating a closure.

What is the role of closures in JavaScript and what… - sobes.tech