JSFiddle - React, Tailwind, and code Playground

by Himanshu Joshi

JavaScript

function buildList(list) {
    var result = [];

    for (var i = 0; i < list.length; i++) {
        var item = 'item' + (i + 1);
        //bad closure - item and i are part of 1 closure and refer to last value of i.
        result.push( function() {console.log(item + ' ' + list[i])} );
       // better - processed each item separately inside this closure.
       // result.push(console.log(item + ' ' + list[i]));
    }
    return result;
}

function testList() {
    var fnlist = buildList([1,2,3]);
    // Using j only to help prevent confusion -- could use i.
    for (var j = 0; j < fnlist.length; j++) {
        fnlist[j]();
    }
}
testList();