Sobes.tech
Junior — Middle

Can you explain what a closure is in programming?

sobes.tech AI

Answer from AI

A closure is a function that "remembers" its lexical environment, meaning the variables accessible at the time of its creation, even if the function is called outside that environment.

Example in JavaScript (Node.js):

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 variable count from the outer function, even after makeCounter has finished executing. This allows for creating private variables and implementing encapsulation.