0

This may be, and possibly is a common question, but I can't find the answer to it, at least not this specific example - which is a common one I believe.

In the below code, why does the program alert 3, 3 times? And why, when let is used, does it work as you would expect?

Is it because when let is used, a new variable is referenced each time or something different? Apologies if this is a bad question - just trying to wrap my head around it...

var arr = [1,2,3];
var o = [];

for(var i = 0; i < arr.length; i++) {
    var val = arr[i];
    o.push(function(){ alert(val); })
}

o.forEach(function(func){func()});
Joshua H
  • 111
  • 1
  • 2
  • 13

1 Answers1

0

All the alerts links to the val variable, which you overwrite.

If you want it to remain unique, then you need to scope it:

var arr = [1, 2, 3];
var o = [];

for (var i = 0; i < arr.length; i++) {
  //closed scope to keep VAL unique
  (function() {
    var val = arr[i];
    o.push(function() {
      alert(val);
    })
  })();
}

o.forEach(function(func) {
  func()
});
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28