JavaScript Using let in loops instead of var (click handlers example)


Example

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