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