Sobes.tech
Middle

What is a closure? Provide an example.

sobes.tech AI

Answer from AI

Closure is a function along with the lexical environment in which it was created. This allows the function to "remember" variables from the outer scope even after the outer function has finished executing.

Example in JavaScript:

function makeCounter() {
  let count = 0;
  return function() {
    count++;
    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 makeCounter, forming a closure.

What is a closure? Provide an example. — Frontend - sobes.tech