What is a closure in JavaScript?

Answer

A closure is a function that remembers and can access variables from its outer (enclosing) scope even after the outer function has finished executing. This happens because inner functions maintain a reference to the variables of their enclosing scope (the lexical environment). Example: function counter() { let count = 0; return function() { return ++count; }; } const inc = counter(); inc(); // 1, inc(); // 2. The returned function is a closure — it "closes over" the count variable. Closures are fundamental to JavaScript and enable: data encapsulation/privacy (the only way to have private variables), the module pattern, memoization, currying, partial application, and factory functions. Every function in JavaScript is a closure over at least the global scope.