Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please provide answer and notes. This one is a real gotcha for many people, so y

ID: 3718319 • Letter: P

Question

Please provide answer and notes.

This one is a real gotcha for many people, so you need to understand it. Be very careful if you are defining a function within a loop: the local variables from the closure do not act as you might first think.

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:

1

2

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 currentvalue 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').

1

2

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

result.push(pointer);

Explanation / Answer

// this function is used to create a list of pushed functions
function buildList(list) {
var result = []; // create an empty array
// for each element in the list
for (var i = 0; i < list.length; i++) {
var item = 'item' + list[i];
// push a function with an alert message
result.push( function() {alert(item + ' ' + list[i])} );
}
return result;
}


// This function is used to test the functionality of pushing a function to an array
function testList() {
// first create a list of three numbers
var fnlist = buildList([1,2,3]);
// using j only to help prevent confusion - could use i
// call the pushed function for each number in the list
for (var j = 0; j < fnlist.length; j++) {
fnlist[j]();
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote