I've grasped the concept of using var
and let
in a for
loop in typescript
/javascript
, but can someone shed light on how and why a const
variable as a loop variable behaves?
for (const i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i)
}, 100 * i);
}
My understanding is that when you declare a variable as const
and assign it a value, that value cannot be changed.
However, it seems that the value is indeed changing in the console.log()
. Shouldn't this trigger an error during compilation? What am I overlooking here?
I've prepared two examples to showcase this behavior.
Could someone provide some insight into this perplexing issue?