Hoisting and Execution Context
What is a closure in JavaScript?
A closure in JavaScript is a function bundled with references to its surrounding lexical environment (the variables available at the location where the function was declared). In simpler terms, a closure gives you access to an outer function's scope from an inner function, even after the outer function has finished executing. Closures are created every time a function is created in JavaScript. The inner function maintains references to the variables from its outer function's scope, allowing it to access those variables even after the outer function has returned. For example: ```javascript function createCounter() { let count = 0; // This variable is enclosed in the returned function's closure return function() { count++; // This function can access and modify the count variable return count; }; } const counter = createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 ``` In this example, the inner function maintains access to the `count` variable even after `createCounter` has finished executing. The `count` variable is private to the returned function - it can't be accessed directly from outside, only through the function calls. This enables powerful patterns like data encapsulation, private variables, function factories, and maintaining state between function calls. Closures are one of the most powerful features in JavaScript.