Register now or log in to join your professional community.
var x,y,funcs=[];for (x=0 ; x<5; x++) { (function(){ funcs.push(function(){ console.log(x); }); }()) }for (y=0; y <5 ; y++ ){ funcs[y]();} I got5 repeated 5 times instead of the expected01234
This is a variable scope issue..
Note that the variable x in the loop is being declared in the global scope .. don’t be fooled by the block curly braces of the loop ... unlike most languages JavaScript's only block element is the function .. so the x inside the function will always see x =5
if you want your piece of code to work right just define a new variable (z for example) at the beginning of the function and print that in the console :
I ran the code in the question in https://jsfiddle.net/j7c6c9t4 and added the fix there.
Thank you
variable x is defined at global scope, by the time it reaches for printing the value of x is 5 at all the instances inside the for loop.
You've got the 5 number 5 times because when the function is push inside funcs array, the 'x' variable is the variable of the global scope. So, when all 5 functions are called, this variable have the value x.
If you want to have the 0,1,2,4,5 expected as result, you have to pass the x variable into the closure on the first loop to isolate the scope.
Below, the script with the result expected :
var x,y,funcs=[];
for (x=0 ; x<5; x++) {
(function(x){
funcs.push(function(){
console.log(x);
});
}(x))
}
for (y=0; y <5 ; y++ ){
funcs[y]();
}