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&rsquo;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&rsquo;s ability to access variables from the parent scope is known as lexical scope. We refer to the parent function&rsquo;s lexical binding of the child function as &ldquo;lexically binding.&rdquo;</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&rsquo;s see and understand closure through an example :</h2> <p><strong>2.1 Example 1:</strong>&nbsp;This example shows the basic use of closure.</p> <pre> function init() { var name = &quot;Closure&quot;; // 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>&nbsp;creates a local variable called&nbsp;<code>name</code>&nbsp;and a function called&nbsp;<code>displayName()</code>. The&nbsp;<code>displayName()</code>&nbsp;function is an inner function that is defined inside&nbsp;<code>init()</code>&nbsp;and is available only within the body of the&nbsp;<code>init()</code>&nbsp;function. Note that the&nbsp;<code>displayName()</code>&nbsp;function has no local variables of its own. However, since inner functions have access to the variables of outer functions,&nbsp;<code>displayName()</code>&nbsp;can access the variable&nbsp;<code>name</code>&nbsp;declared in the parent function,&nbsp;<code>init()</code>.</p> <p><a href="https://medium.com/@radheshayamkumar071/closure-in-javascript-bb328c3fa948">Website</a></p>