-
Consider the following code snippet :
function constfunctions()
{
var functions = [];
for(var k = 0; k < 10; k++)
functions [k] = function() { return k; };
return functions ;
}
var functions = constfunctions();
functions [5]()
What does the last statement return ?
-
- 10
- 9
- 0
- All of above
- None of these
Correct Option: A
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 k. When constfuncs() returns, the value of the variable k is 10, and all 10 closures share this value. Therefore, all the functions in the returned array of functions return the same value.