What is closure in JavaScript

A closure in JavaScript is a feature where an inner function has access to the outer function's variables, even after the outer function has finished executing. This allows the inner function to "close over" its environment, hence the term "closure." Closures are commonly used to preserve state in asynchronous programming and for private data encapsulation.

Here’s a simple example of a closure in JavaScript:

function outerFunction() { let outerVariable = 'I am outside!'; function innerFunction() { console.log(outerVariable); } return innerFunction; } const inner = outerFunction(); inner(); // Output: I am outside!

keywords: JavaScript closure inner function outer function variables