The Magic of Lexical Environment
JavaScript is a language with functional memory. Functions " remember " where they were created and what variables were available to them.
What is a closure?
It is a function's ability to remember its lexical scope even after the outer function has finished executing.
function createCounter() {
let count = 0;
return function() {
return count++;
};
}
let counter = createCounter();
alert(counter()); // 0
alert(counter()); // 1
How does it work?
Inside every function, there is a hidden property [[Environment]] that stores a reference to its birthplace.
Important
Closures allow you to create private variables that cannot be accessed from the outside except through special functions.
Note
All functions in JavaScript are naturally closures (except those created via new Function).