3
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?

brso05
  • 13,142
  • 2
  • 21
  • 40
Novellizator
  • 13,633
  • 9
  • 43
  • 65

1 Answers1

2

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

Shreeram K
  • 1,719
  • 13
  • 22