<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Levi Meahan</title>
    <description>The latest articles on DEV Community by Levi Meahan (@levimeahan).</description>
    <link>https://dev.to/levimeahan</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F128727%2Fef73ec16-e837-4326-a9f3-bc9c2ffb7a3d.jpg</url>
      <title>DEV Community: Levi Meahan</title>
      <link>https://dev.to/levimeahan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/levimeahan"/>
    <language>en</language>
    <item>
      <title>Closures/Scope and the setTimeout for loop question</title>
      <dc:creator>Levi Meahan</dc:creator>
      <pubDate>Sun, 19 May 2019 00:43:14 +0000</pubDate>
      <link>https://dev.to/levimeahan/closures-scope-and-the-settimeout-for-loop-question-5bl6</link>
      <guid>https://dev.to/levimeahan/closures-scope-and-the-settimeout-for-loop-question-5bl6</guid>
      <description>&lt;p&gt;I've researched the event loop in JavaScript before, and have a decent general understanding of how it works, but I was recently caught off guard by this classic interview question. &lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// What does the below code output?&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="nx"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Answer: 4 4 4 4&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;I've seen this around and remembered that it's a trick question, and there are some ways to solve it like using &lt;code&gt;let i = 0;&lt;/code&gt; instead of &lt;code&gt;var i = 0;&lt;/code&gt; but I didn't fundamentally understand why that worked. (If you want a great, very detailed explanation of this question, check out this post: &lt;a href="https://medium.freecodecamp.org/thrown-for-a-loop-understanding-for-loops-and-timeouts-in-javascript-558d8255d8a4"&gt;https://medium.freecodecamp.org/thrown-for-a-loop-understanding-for-loops-and-timeouts-in-javascript-558d8255d8a4&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;But there was still one thing I didn't get. The callback gets put into the event queue, so certainly it has to keep a copy of &lt;code&gt;i&lt;/code&gt; in order to use it, right? Since  our main code is going to finish running before the callback gets called, shouldn't the variable &lt;code&gt;i&lt;/code&gt; not exist anymore? I didn't see an explanation, so I went to go review MDN's article on &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures"&gt;Closures&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;The article explains - Closures (aka the callback we pass to setTimeout) keep a reference to the environment/scope they were created in, including references to its variables, even after that environment/scope stops running. Ohhhh. Suddenly this makes a lot more sense. Even after our main code finishes, a reference to its variables(at a minimum, the ones the closure uses) is kept around for the closure to access. So if the &lt;code&gt;i&lt;/code&gt; used in our callback is a global variable within that environment, the closure will use that reference. &lt;/p&gt;

&lt;p&gt;Thus, the many solutions to this question revolve around creating a different scope for &lt;code&gt;i&lt;/code&gt; to exist in &lt;strong&gt;each time we call setTimeout&lt;/strong&gt;, so that each callback in the event queue maintains a reference to a completely different variable, and we really have 4 different variables all named &lt;code&gt;i&lt;/code&gt;, in different scopes.&lt;/p&gt;

&lt;p&gt;Which actually raises an interesting, not completely obvious behavior of the following solution:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="nx"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// 0 1 2 3&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;For this to work, we know that &lt;code&gt;i&lt;/code&gt; needs to actually be a different variable each time we call setTimeout. Which means that when we use &lt;code&gt;let&lt;/code&gt; in a for loop like this, it's actually creating a new variable named &lt;code&gt;i&lt;/code&gt; on every iteration of the loop. Never really thought about it like that!&lt;/p&gt;

&lt;p&gt;And this also raises a somewhat important bit of performance knowledge to keep in mind - if we maintain a reference to a closure, we're maintaining a reference to the entire scope it was defined in (even with possible compiler optimization, it's at least the variables used within the closure).&lt;/p&gt;

&lt;p&gt;Further reading that explains much more about closures and scope: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"&gt;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures"&gt;https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>closures</category>
      <category>eventloop</category>
      <category>interviewquestions</category>
    </item>
  </channel>
</rss>
