Sobes.tech
Middle+

What is a closure in JavaScript? Where is it used in practice?

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 an outer function even after the outer function has finished executing.

In practice, closures are often used to create private variables, implement functions with preserved state, or when working with asynchronous code.

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 closes over the variable count, preserving its value between calls.