Examveda
Examveda

Consider the following code snippet :
var c = counter(), d = counter(); 
function constfuncs() 
{
    var funcs = [];
    for(var i = 0; i < 10; i++)
        funcs[i] = function() { return i; };
    return funcs;
}
var funcs = constfuncs();
funcs[5]()
What does the last statement return ?

A. 9

B. 0

C. 10

D. None of the mentioned

Answer: Option C

Solution(By Examveda Team)

The code above creates 10 closures, and stores them in an array. The closures are all defined within the same invocation of the function, so they share access to the variable i. When constfuncs() returns, the value of the variable i is 10, and all 10 closures share this value. Therefore, all the functions in the returned array of functions return the same value.

This Question Belongs to Javascript >> Array And Function

Join The Discussion

Related Questions on Array and Function