Communiquez avec les autres et partagez vos connaissances professionnelles

Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.

Suivre

When running this JavaScript code, I got a result i didn't except .. why is that?

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

user-image
Question ajoutée par Rana Alnajjar , Web developer , Lebcards
Date de publication: 2015/07/02
Rahaf Nawash
par Rahaf Nawash , Front End Engineer , Atypon Systems Inc.

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

aniket kavlekar
par aniket kavlekar , Software Engineer / Web Developer , Hexagon Capability Center Private Limited

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. 

Jonathan de Flaugergues
par Jonathan de Flaugergues , software engineer , Abbeal

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]();

More Questions Like This

Avez-vous besoin d'aide pour créer un CV ayant les mots-clés recherchés par les employeurs?