I am facing hard time understanding this piece of JS code

51 views Asked by At
var myAlerts = [];    

for (var i = 0; i < 5; i++) {    
    myAlerts.push(    
        function inner() {    
            alert(i);    
        }    
    );    
}    

myAlerts[0](); // 5    
myAlerts[1](); // 5    
myAlerts[2](); // 5   
myAlerts[3](); // 5   
myAlerts[4](); // 5 

why the all the values at positions 0-4 in array are "5". I found some article regarding this as Javascript supports Lexical scoping rather than Dynamic. Yes, I got that. But is there any way to understand this core concept for the above snippet Thank you

1

There are 1 answers

0
Dnyanesh On BEST ANSWER

In this particular functionality value i is dynamic and it will be replaced with new value whenever you make change in value of i.

i is getting considered as value by reference.

So if you you change it to for loop till 10 you will have all i's replaced with 10.