Sobes.tech
Middle

What is a closure in JavaScript? Provide an example.

sobes.tech AI

Answer from AI

A closure in JavaScript is a function that 'remembers' its lexical environment, even if it is called outside its original scope. This allows the function to have access to variables from the outer function after the outer function has finished executing.

Example:

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, creating a closure.

What is a closure in JavaScript? Provide an example… - sobes.tech