What is a closure in Javascript?
Introduction
In JavaScript, internal and external functions exist, and internal functions can access local variables of external functions. Also, even after the outer function is destroyed, the inner function can access the variables of the outer function. Closures take advantage of this property. Let's look at an example.
💡Function Example
function outter() {
let title = 'hello everyone';
return function () {
alert(title);
};
}
inner = outter();
inner();
The above code defines the outer function , returns the function to the inner function , and stores the execution result of the outer function in the inner variable.
🔍 Example code execution result
hello everyone
When you run the code, a warning window 'hello everyone' is displayed as shown in the picture above. 'coding everybody' is the value contained in the title, which is a local variable of the external function. The properties of the closure that can be seen in the example above are
inner = outter();
In the above code, the outer function returns the inner function, even though the outer function is terminated.
inner();
Afterward, when the inner function is called, the title variable existing in the outer function can be accessed.
In other words, the characteristic of closures is that not only can the external function containing the internal function be accessed but also the external function and local variables of the external function can be accessed through the internal function even after the external function is terminated.