Click here to Skip to main content
15,888,579 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How would this code be written, and output the same result, if you used the let keyword rather than the var keyword

JavaScript
function constfuncs() {
    var funcs = [];
    for(var i = 0; i < 10; i++) 
       funcs[i] = function() { return i; };
    return funcs;
}

var funcs = constfuncs();
console.log(funcs[5]()); //Outputs 10



What I have tried:

I don't fully understand JavaScript hoisting, so I wanted to see how this piece of code would work when using a more understandable type of variable
Posted
Updated 9-May-18 13:55pm

1 solution

var declares a global variable while let declares a variable to a limited scope. In this case, the scope of the variable is inside the loop. Outside the loop, i doesn't exist.

If you leave this as var, the scope of the variable is the end constfuncs() function.

See this[^] for more information.
 
Share this answer
 
v2
Comments
Member 13814166 9-May-18 20:13pm    
I'm having trouble understanding how i in "function() { return i; };" is always 10. I thought only the declaration of i would be hoisted up, not the value it contained, am I incorrect in thinking this, or is there something I'm missing?

I would have assumed, if the output was the same, it would be written like this with lets rather than vars:

let i; //The declaration is hoisted up
function constfuncs() {
var funcs = [];
for(i = 0; i < 10; i++)
funcs[i] = function() { return i; };
return funcs;
}

var funcs = constfuncs();
console.log(funcs[5]()); //Outputs 5
Dave Kreskowiak 9-May-18 20:57pm    
OK, this is different from what you asked above.

You're creating an array of functions, all of which are "return i;", NOT "return the current value of i at the time the function instance was created and put into the array.

At the end of the loop, the value of i is 10, so I'm not surprised every instance of the function returns 10.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900