Click here to Skip to main content
15,900,461 members

Comments by Member 13814166 (Top 3 by date)

Member 13814166 9-May-18 20:13pm View    
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
Member 13814166 6-May-18 13:33pm View    
Deleted
Sorry for my stupidity, but I still do not understand. When I do this:

var t=0;
var a=t;
t+=1;
var b=t;

a is 0, and b is 1. Why are they not the same?

And thank you so much for sparing your time to help me :D
Member 13814166 6-May-18 13:24pm View    
Ok, I understand, but why, if instead of let i=0 the for loop created var i=0, does the function print "10" ten times? I would expect the items of the funcs array to have the same values as when the for loop used let i=0?