Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function always resulting in same number [duplicate]

Tags:

javascript

I have the below function which always results me 5. I see that the function inner is getting executed in the global context, so the result is 5 always.

I tried to wrap the entire loop inside a closure, so that it creates a new scope yet it failed.

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

Can anyone tell me on how to fix this scoping issue here?

like image 516
Shane Avatar asked May 16 '26 10:05

Shane


2 Answers

Try closures:

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

Wrapping the function in a closure works:

var myAlerts = [];

for (var i = 0; i < 5; i++) {
  myAlerts.push((function(i) {
    return function inner() {
      alert(i);
    }
  })(i));
}
like image 31
tomasbasham Avatar answered May 17 '26 22:05

tomasbasham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!