Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Moving Objects Databases

Authors: Ralf Hartmut Güting, Markus Schneider

1st Edition

0120887991, 978-0120887996

More Books

Students also viewed these Databases questions