Question: You need to fix bug with a loop and closures, javascript Note you need to add a line that actually calls testList(); because there is

You need to fix bug with a loop and closures, javascript

Note you need to add a line that actually calls testList(); because there is no button like on the site to execute the code.

function buildList(list) {

var result = [];

for (var i = 0; i < list.length; i++) {

var item = 'item' + list[i];

result.push( function() {alert(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]();

}

}

The line result.push( function() {alert(item + ' ' + list[i])} adds a reference to an anonymous function three times to the result array. If you are not so familiar with anonymous functions think of it like:

pointer = function() {alert(item + ' ' + list[i])};

result.push(pointer);

Note that when you run the example, "item3 undefined" is alerted three times! This is because just like previous examples, there is only one closure for the local variables for buildList. When the anonymous functions are called on the line fnlist[j](); they all use the same single closure, and they use the current value for i and item within that one closure (where i has a value of 3 because the loop had completed, and item has a value of 'item3').

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!