Closure in JavaScript
<p>A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.</p>
<p><strong>Lexical Scoping:</strong></p>
<p>A function scope’s ability to access variables from the parent scope is known as lexical scope. We refer to the parent function’s lexical binding of the child function as “lexically binding.”</p>
<p><img alt="" src="https://miro.medium.com/v2/resize:fit:630/0*w7mjWzwtP_t2Uo1Z" style="height:467px; width:700px" /></p>
<h2>2. Let’s see and understand closure through an example :</h2>
<p><strong>2.1 Example 1:</strong> This example shows the basic use of closure.</p>
<pre>
function init() {
var name = "Closure"; // name is a local variable created by init
function displayName() {
// displayName() is the inner function, that forms the closure
console.log(name); // use variable declared in the parent function
}
displayName();
}
init();</pre>
<p><code>init()</code> creates a local variable called <code>name</code> and a function called <code>displayName()</code>. The <code>displayName()</code> function is an inner function that is defined inside <code>init()</code> and is available only within the body of the <code>init()</code> function. Note that the <code>displayName()</code> function has no local variables of its own. However, since inner functions have access to the variables of outer functions, <code>displayName()</code> can access the variable <code>name</code> declared in the parent function, <code>init()</code>.</p>
<p><a href="https://medium.com/@radheshayamkumar071/closure-in-javascript-bb328c3fa948">Website</a></p>