Closures in JavaScript are a powerful concept that allows functions to retain access to variables from their parent scope even after the parent function has finished executing. In simpler terms, a closure is a function bundled together with its lexical environment (the variables and functions that were in scope at the time it was created).
Closures are created whenever a function is defined within another function, and the inner function has access to the outer function’s variables. This is possible because JavaScript has lexical scoping, which means that functions are executed using the variable scope that was in effect when they were defined, not when they are executed.
Here’s an example of a closure in JavaScript:
function outerFunction() { var outerVariable = 'I am from the outer function'; function innerFunction() { console.log(outerVariable); } return innerFunction; } var closure = outerFunction(); closure(); // Output: I am from the outer function
In the above example, the innerFunction is defined inside the outerFunction and has access to the outerVariable even after the outerFunction has finished executing. When we invoke outerFunction and assign its return value to the closure variable, we essentially create a closure. Later, when we call closure(), it still has access to the outerVariable and logs its value.
Closures are commonly used in JavaScript for various purposes, such as creating private variables, implementing data hiding, and creating functions with persistent state. They provide a way to encapsulate data and behavior within a function, making it a powerful tool for writing modular and reusable code.