Sobes.tech
Junior — Middle

Explain what closures are in JavaScript and how they work.

sobes.tech AI

Answer from AI

Closures in JavaScript are functions that 'remember' the environment in which they were created, including access to variables from outer functions even after the outer function has finished executing.

This allows the inner function to access and preserve the state of variables from the outer function.

Example:

function makeCounter() {
  let count = 0;
  return function() {
    count++;
    return count;
  };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2

Here, the function returned from makeCounter closes over the variable count, allowing it to preserve and modify its value between calls.