A

Admin • 828.03K Points
Coach

Q. 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
  • Correct Answer - Option(C)
  • Views: 7
  • Filed under category JavaScript
  • Hashtags:

Explanation by: Admin
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.

You must be Logged in to update hint/solution

Discusssion

Login to discuss.

Be the first to start discuss.