Closures in JavaScript
Let's now study the concept of closure. In fact, you are already familiar with this concept, it remains only to learn the correct terminology.
So a closure is a function along with all the external variables that are available to it. Or, in other words, a closure is a function along with its lexical environment.
In JavaScript, most often, when they say "function closure", they do not mean this function itself, but its external variables. If some function gets a variable from its lexical environment, then we say "the variable is taken from the closure".
Let's remember the code we made in the previous lesson:
function test() {
let num = 1;
return function() {
console.log(num);
}
}
let func = test();
func(); // shows 1
In this case, we can say that the function
func
gets the value of the variable
num
from the closure. We can also
say that the function func
stores
the value of the variable num
in a closure.