Using let in loops instead of var click handlers example

suggest change

Let’s say we need to add a button for each piece of loadedData array (for instance, each button should be a slider showing the data; for the sake of simplicity, we’ll just alert a message). One may try something like this:

for (var i = 0; i < loadedData.length; i++) {
    jQuery("#container").append("<a class='button'>"+loadedData[i].label+"</a>")
        .children().last() // now let's attach a handler to the button which is a child
        .on("click",function() { alert(loadedData[i].content); });
}

But instead of alerting, each button will cause the

TypeError: loadedData[i] is undefined

error. This is because the scope of i is the global scope (or a function scope) and after the loop, i == 3. What we need is not to “remember the state of i”. This can be done using let:

for (let i = 0; i < loadedData.length; i++) {
    jQuery("#container").append("<a class='button'>"+loadedData[i].label+"</a>")
        .children().last() // now let's attach a handler to the button which is a child
        .on("click",function() { alert(loadedData[i].content); });
}

An example of loadedData to be tested with this code:

var loadedData = [
    { label:"apple",      content:"green and round" },
    { label:"blackberry", content:"small black or blue" },
    { label:"pineapple",  content:"weird stuff.. difficult to explain the shape" }
];

A fiddle to illustrate this

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Scope:
* Using let in loops instead of var click handlers example

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde