What is this problem in JavaScript’s selfexecuting anonymous function?

JavascriptWeb DevelopmentObject Oriented Programming

<p>Let&rsquo;s say here is a sample code snippet and we are required to tell the possible output for this snippet and provide an explanation for it</p><pre class="prettyprint notranslate">var name = &#39;Zakir&#39;; (() =&gt; { &nbsp; &nbsp;name = &#39;Rahul&#39;; &nbsp; &nbsp;return; &nbsp; &nbsp;console.log(name); &nbsp; &nbsp;function name(){ &nbsp; &nbsp; &nbsp; let lastName = &#39;Singh&#39;; &nbsp; &nbsp;} })(); console.log(name);</pre><p>Let&rsquo;s go through this problem line by line with a naive approach</p><p>1 &rarr; &lsquo;Zakir&rsquo; stored in variable name</p><p>3 &rarr; We enter inside a self-executing anonymous function</p><p>4 &rarr; The variable name is reinitialized to &lsquo;Rahul&rsquo;</p><p>5 &rarr; return statement is encountered, so we exit the function</p><p>15 &rarr; print the name variable to screen whose current value is &lsquo;Rahul&rsquo;</p><p>So, the final output will be</p><pre class="result notranslate">Rahul</pre><p>But, unfortunately, it&rsquo;s wrong, let&rsquo;s go through the code once again to see where we went wrong, this time keeping the concept of variable and function hoisting in mind.</p><p>1 &rarr; &lsquo;Zakir&rsquo; stored in variable name</p><p>3 &rarr; We enter inside a self-executing anonymous function</p><p>As we enter the function, function hoisting takes on and the function name() which is defined at the bottom of the self-executing function is hoisted to very top of the self-executing function And at that intermediate state the code would be something like &minus;</p><h2>Example</h2><pre class="prettyprint notranslate">let name = &#39;Zakir&#39;; (() =&gt; { &nbsp; &nbsp;let name; &nbsp; &nbsp;name = &#39;Rahul&#39;; &nbsp; &nbsp;return; &nbsp; &nbsp;console.log(name); &nbsp; &nbsp;name = function(){ &nbsp; &nbsp; &nbsp; let lastName = &#39;Singh&#39;; &nbsp; &nbsp;} })(); console.log(name);</pre><p>Note that whenever a variable/function is hoisted to the top of its scope it&rsquo;s only defined and initialised, it is initialised at its actual position, at the top it is undefined, but it exists.</p><p>So, when the variable name is reinitialised it&rsquo;s the local variable name which gets reinitialized and not the global variable so, after this we return out of the self-executing function and print the global variable name to the console, which still holds &lsquo;Zakir&rsquo;. Therefore, the output will be &minus;</p><h2>Output</h2><pre class="result notranslate">Zakir</pre>
raja
Updated on 18-Aug-2020 07:27:22

Advertisements