Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using const as loop variable in for loop

I understand the behavior of using var and let in for loop in typescript/javascript but can someone explain why and how a const variable as a loop variable behaves ?

for (const i = 0; i < 5; i++) {
  setTimeout(function() {
    console.log(i)
  }, 100 * i);
}

From what i understand , when you declare a variable as const and initialize its value , the value cannot be changed

Yet you can see the value being changed in the console.log() .An error has to be thrown while compilation right ?What am i missing here ?

I have created 2 examples for this behavior .

Loop variable as a const

Const variable re assignment

Can someone help me understand this ?

like image 717
CruelEngine Avatar asked Jul 15 '26 13:07

CruelEngine


1 Answers

It works in Stackblitz because it is running traspiled code:

AppComponent.prototype.test = function () {
    var _loop_1 = function (i) {
        setTimeout(function () {
            console.log(i);
        }, 100 * i);
    };
    for (var i = 0; i < 5; i++) {
        _loop_1(i);
    }
};

It won't work if you add a snippet here because it is not transpiled

for (const i = 0; i < 5; i++) {
  setTimeout(function() {
    console.log(i)
  }, 100 * i);
}

enter image description here

like image 184
adiga Avatar answered Jul 17 '26 15:07

adiga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!