Sobes.tech
Middle+

What is a closure?

sobes.tech AI

Answer from AI

Closure is a function that "remembers" the environment in which it was created, including access to variables from the outer scope, even after the outer function has finished executing.

This allows the function to use and modify variables declared outside its body, which is often used to create private variables or functions with preserved state.

Example in JavaScript:

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.

What is a closure? — Frontend - sobes.tech