Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is a classic JavaScript confusion between "scope" and "curly braces". It turns out that curly braces have little to do with scope in JavaScript. Scope only arises from <em>functions</em>.</p> <p>One consequence of this is that variables are always hoisted to the top of the scope, i.e. the nearest function. So your code is exactly equivalent to:</p> <pre><code>var all_cookies = [1,2,3,4,5,6]; var i; var route_num; var list_item; var newLi; for (i = 0; i &lt; all_cookies.length; i++) { route_num = all_cookies[i]; list_item = "&lt;li&gt;&lt;a href='#saved-route'&gt;"; list_item += "&lt;p&gt;" + route_num + "&lt;/p&gt;&lt;/a&gt;&lt;/li&gt;"; newLi = $(list_item); newLi.bind('click', function(){ alert(route_num); }); $('#saved-list').append(newLi); } </code></pre> <p>With this in mind, you can see how, since <code>route_num</code> is the same variable every time through the loop, after the loop is over its value is set to <code>6</code>, and in the future whenever the click handler is called, the <code>6</code> is what you see.</p> <p>One way to fix this is to wrap the contents of your loop in a self-executing anonymous function:</p> <pre><code>var all_cookies = [1,2,3,4,5,6]; for (var i = 0; i &lt; all_cookies.length; i++) { (function () { var route_num = all_cookies[i]; var list_item = "&lt;li&gt;&lt;a href='#saved-route'&gt;"; list_item += "&lt;p&gt;" + route_num + "&lt;/p&gt;&lt;/a&gt;&lt;/li&gt;"; var newLi = $(list_item); newLi.bind('click', function(){ alert(route_num); }); $('#saved-list').append(newLi); }()); } </code></pre> <p>That way, when the variables get hoisted, they will just get hoisted to the top of that inner self-executing function, and so there will be different instances of them for each run through the loop.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload