Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does let in for loop work? [duplicate]

var messages = ["Check!", "This!", "Out!"];

for (var i = 0; i < messages.length; i++) {
  setTimeout(function () {
    console.log(messages[i]);
  }, i * 1500);
}
// -> prints 3* undefined


for (let i = 0; i < messages.length; i++) {
  setTimeout(function () {
    console.log(messages[i]);
  }, i * 1500);
}
// -> prints out the array

I understand how "var" works and I'm quite used to it - the scope is functional. However the let statement is far from clear. I understand is has block scope, but why does THAT matter in the example? In that example the for loop is long time over with in both cases. Why does let print out the array?

like image 638
Novellizator Avatar asked Jul 14 '26 00:07

Novellizator


1 Answers

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Check out here more detailed info https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let

like image 197
Shreeram K Avatar answered Jul 15 '26 14:07

Shreeram K



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!