1

I have a VERY basic problem about JavaScript that is driving me nuts! This should be simple, but it is not. I am writing a JavaScript function, without any other interference such as jQuery and similar.

What I am doing is this:

var myArray = [{name: 'Dolan', age: 34},{name: 'Agroy', age: 133}];
for (var character in myArray) {
   var ch = myArray[character];
   var divvie = document.createElement('div');
   divvie.addEventListener('click', function () { alert(ch.name); });
}

But the problem is that the alert always returns "Agroy" in this case.. it does not provide a "snapshop" of the ch.name as it was when the event was hooked up, but rather how it looks when the entire loop has completed.

That this is not working is just stupid. It is probably trivial.

Christoffer
  • 545
  • 1
  • 5
  • 19
  • Some code has been omitted for keeping this post brief. – Christoffer Feb 11 '18 at 21:36
  • The reason why it's not working is this: You run a loop where you assign a new value to the variable on each iteration. You also define a function that can use that variable sometime in the future. When your loop ends, the variable is set to the last assigned value, so if any of the functions that you have defined is run in the future, they will all use the current value of the variable, which is still the last assigned value. You can solve it very easily by defining the variable with `let` instead of `var. `let` defined the variable in a block-scope, and it will work as you expect. – some Feb 11 '18 at 21:44
  • Ah, I see, did not know about "let". Is it advicable to always use `let` instead of `var`? – Christoffer Feb 12 '18 at 12:48

0 Answers0