0

So I have a block of code like this:

var hello3 = [];

  function testfunc3() {
    let i = 0;
    while (i < 10) {
      hello3[i] = {
        another3: function() {
          return i;
        }
      };
      i++;
    }
  }

  function alertnow3() {
    alert(hello3[6].another3());
  }

When I call testfunc3 first, and then call alertnow3, the alert I am getting is "10"

Then I changed the code block to this:

var hello1 = [];

  function testfunc1() {
    for (let i = 0; i < 10; i++) {
      hello1[i] = {
        another1: function() {
          return i;
        }
      };
    }
  }

  function alertnow1() {
    alert(hello1[6].another1());
  }

Now when I call testfunc1 first, and then call alertnow1, the alert I am getting is "6"

Then I changed the code to this:

var hello2 = [];

  function testfunc2() {
    for (let i = 0; i < 10; ) {
      hello2[i] = {
        another2: function() {
          return i;
        }
      };
      i++;
    }
  }

  function alertnow2() {
    alert(hello2[6].another2());
  }

Now when I call testfunc2 first, and then call alertnow2, the alert I am getting is "7"

Why are the responses different for the 3 blocks of code? I was expecting all responses to be 6.

Here is a codesandbox link for you guys to check (All 3 cases given above is demonstrated in the code. Click on "Click Here" first and then "Alert Now": https://codesandbox.io/s/nostalgic-microservice-mtl1t?file=/src/App.js:329-577

Adam
  • 657
  • 2
  • 9
  • 22
  • 2
    [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486) – adiga May 19 '20 at 18:59
  • I am aware of closures, so I used let instead of var for all initializations. Are you sure this is the reason in my case? – Adam May 19 '20 at 19:14

0 Answers0