1 answer

Please provide correct answer as well as notes to how it was reached. This one is...

Question:

Please provide correct answer as well as notes to how it was reached.

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.

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

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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]();

    }


Answers

// 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
//The line result.push( function() {alert(item + ' ' + list[i])} add
// 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. pointer = function() {alert(item + ' ' + list[i])}; => an anonymous function
// 2. result.push(pointer); => poiter to an anonymous function pushed to result array
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]();
}
}

/*
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').
*/

Note: I did not find any question in this post.

Hence, I have provided the description of this code snippet.

.

Similar Solved Questions

1 answer
X-ray facil 9. During wWI Marie and Irene Curie (her daughter) rigged automoe to be kno...
X-ray facil 9. During wWI Marie and Irene Curie (her daughter) rigged automoe to be kno which could be brought directly to the battlefield. These vehicles c came to be known as " Answer: 10. The discovery of radium was quickly commercialized. In one case a fake person by the name of was created ...
1 answer
Annual Cash Company Dividend per share $18.00 15.00 14.90 Market Value per Share $ 230.77 151.52...
Annual Cash Company Dividend per share $18.00 15.00 14.90 Market Value per Share $ 230.77 151.52 165.56 117.10 3 4 Compute the dividend yield for each of these four separate companies. Ovidend Yield Choose Denominator Company Choose Numerator: Dividend Yield Dividend yield ► 1 . 2. 3 4 1 Which...
1 answer
2. The following data is available for John H. Corporation at December 31, common stock: authorize...
2. The following data is available for John H. Corporation at December 31, common stock: authorize shares 100,000 shares; issued number of shares 60,000 shares; treasury number of shares 5,000. If the Corporation pays a dividend of $2 per share, what is the total amount of the dividend paid to the c...
1 answer
Exercise 6-4 Basic Segmented Income Statement [LO6-4] Royal Lawncare Company produces and sells two packaged products—Weedban...
Exercise 6-4 Basic Segmented Income Statement [LO6-4] Royal Lawncare Company produces and sells two packaged products—Weedban and Greengrow. Revenue and cost information relating to the products follow: Product Weedban Greengrow Selling price per unit $ 8.00 $ 38.00 Variable expenses per unit ...
1 answer
3. Show how the compounds below can be made in two different ways in a single...
3. Show how the compounds below can be made in two different ways in a single step (one reaction) from the appropriate starting materials. the Ste a) a Grignard reagent a Grignard reagent OH an epoxide a different epoxide b) an alcohol a diene c) OH an alkyl halide an alkene d) a bromoalcohol 2 a di...
1 answer
4. If a suspended object A is attracted to a charged object B, can we conclude...
4. If a suspended object A is attracted to a charged object B, can we conclude that A is charged? Explain your answer....
1 answer
Given the following while loop, what is the value assigned to variable z for the given...
Given the following while loop, what is the value assigned to variable z for the given values of variables a, b and c? mult = 0; while (a < 10) { mult = b * a; if (mult > c) { break; } a = a + 1; } z = a; a = 4, b = 5, c = 20...
1 answer
17. Teacher salaries: A random sample of 50 public school teachers in Georgia had a mean...
17. Teacher salaries: A random sample of 50 public school teachers in Georgia had a mean annual salary of $48,300. Assume the population standard deviation is σ = $8,000. Can you conclude that the mean salary of public school teachers in Georgia differs from $50,000? Use the α = 0.01 l...
1 answer
Find the interval(s) where the function is concave down. 10- 8 6 -10-8-674 LS 16 8...
Find the interval(s) where the function is concave down. 10- 8 6 -10-8-674 LS 16 8 10 O A. (-00. - 1)U(2.0) OB. (-2.3) OC. (-1, 2) OD. (-0. - 2)U(3.00)...
1 answer
Two charged spheres are brought together and separated. What is the final charge for each sphere?
Two charged spheres are brought together and separated. What is the final charge for each sphere?...
1 answer
Can anyone identify this plant for me? I have been looking all over the internet. This...
Can anyone identify this plant for me? I have been looking all over the internet. This plant is very tall, has lots of yellow flowers clustered together in many different regions of the plant. This picture was taken in September of 2016 in Pennsylvania...
1 answer
250. The school nurse is teaching the faculty is the most effective methods to prevent the...
250. The school nurse is teaching the faculty is the most effective methods to prevent the spread of lice (Pediculus 250. The school nurse is teaching the faculty the most effective methods to prevent the spread of lice (pediculus Humanus Capitis) in the school. The information that would be most im...
1 answer
Problem 5.11 Your brother has asked you for a loan and has promised to pay you...
Problem 5.11 Your brother has asked you for a loan and has promised to pay you $5,450 at the end of three years. If you normally invest to earn 7.60 percent per year, how much will you be willing to lend to your brother if you view this purely as a financial transaction (i.e., you don't give you...
1 answer
Question 1 - Selection of an activity base Fantastic Sweepers of New England manufactures replacement rotary...
Question 1 - Selection of an activity base Fantastic Sweepers of New England manufactures replacement rotary sweeper brooms for large sweeper trucks that clear leaves and snow from city streets. The business is highly seasonal, with the largest demand during and just preceding the fall and winter mo...
1 answer
What kinds of animal cells might have a lot mitochondria present
What kinds of animal cells might have a lot mitochondria present?...
1 answer
A person is nearsighted with a near point of 75. cm. (a) What FOCAL LENGTH is...
A person is nearsighted with a near point of 75. cm. (a) What FOCAL LENGTH is this? (b) What POWER lens is needed to correct their nearsightedness (assuming distance from lens to eye is negligible)?...
1 answer
Find the volume of a cube with a cylindrical hole of diameter of 68mm
Find the volume of a cube with a cylindrical hole of diameter of 68mm?It is a perfect cube with each side of 84mmThank you....