-1

I have a block of code:

const calculatenumbers = [];
for (var i = 1; i <= 5; i++) {
  var myindex = i;
  calculatenumbers.push(() => {
    var calculatednumber = myindex * 100;
    console.log('my number is:' + calculatednumber);
  });
}



for (var j = 0 ; j < calculatenumbers.length; j++) {
calculatenumbers[j]();
}

the output of this code is:

my number is:500
my number is:500
my number is:500
my number is:500
my number is:500

Why the code output five times 'my number is:500' instead of

my number is:100
my number is:200
my number is:300
my number is:400
my number is:500
JavaScript Rookie
  • 153
  • 1
  • 3
  • 10
  • 3
    I don't see (nor expect) any output for this code on the Chrome console. You're just pushing a function inside the array and not calling that function. – Pratyush Vashisht Aug 23 '21 at 18:39
  • I've updated the question, please review it again. – JavaScript Rookie Aug 23 '21 at 18:44
  • 3
    `var` is hoisted so the value of `myindex` is `5` for every function call. – Krisztián Balla Aug 23 '21 at 18:45
  • 3
    Replace `var myindex = i` with `let myindex = i` and it will work as you intended. – trincot Aug 23 '21 at 18:46
  • You could pass the index as an argument, like this: const calculatenumbers = []; for (var i = 1; i <= 5; i++) { calculatenumbers.push((myindex) => { var calculatednumber = myindex * 100; console.log('my number is:' + calculatednumber); }); } for (var j = 0 ; j < calculatenumbers.length; j++) { calculatenumbers[j](j); } – Izac Cavalheiro Aug 23 '21 at 18:51
  • 2
    @Andy `push` accepts anything, it simply takes whatever it gets and adds it to the array. – Lennholm Aug 23 '21 at 18:51
  • 2
    @Andy, an array can hold anything. You're just pushing a function in place of primitive variables. – Pratyush Vashisht Aug 23 '21 at 18:52
  • Your current code would work if JS was asynchronous and ran on one thread. – Rojo Aug 23 '21 at 18:53
  • @ kindall Can I ask why the index is 5 when the callback function is called, shouldn't be the case that each time the callback is called, it receives the corresponding index (1, 2, 3, 4, 5) – JavaScript Rookie Aug 23 '21 at 19:48

1 Answers1

0

you can use let, don't use var in loop function

const calculatenumbers = [];
for (var i = 1; i <= 5; i++) {
  let myindex = i;
  calculatenumbers.push(() => {
    var calculatednumber = myindex * 100;
    console.log('my number is:' + calculatednumber);
  });
}



for (var j = 0; j < calculatenumbers.length; j++) {
  calculatenumbers[j]();
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Viktor M
  • 301
  • 1
  • 7