In JavaScript, closure is a function that has access to the outer function's variables even after the outer function has returned. It is created by returning an inner function from the outer function. The inner function can still access the outer function's variables because it was defined within the scope of the outer function.
Closures are useful for creating private functions or maintaining state between function calls. They also help in avoiding naming collisions and making code more reusable.
Here is an example of a closure in JavaScript:
function outerFunction(num) {
let counter = num;
return function innerFunction() {
console.log(counter);
counter--;
};
}
let incrementCounter = outerFunction(5);
incrementCounter(); // logs 5
incrementCounter(); // logs 4