0

Here are the two code snippets, I am using "var" keyword in one and "let" in another. why the outcomes are so different.

for (let i = 0; i < 5; i++) {
  setTimeout(function() {
    console.log(i);
  }, 100);
}
output: 0 1 2 3 4

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

Output: 5 5 5 5 5

Ada_lovelace
  • 637
  • 2
  • 6
  • 18
  • 1
    tl;dr: Because `let` is block scoped and `var` is not. – Felix Kling Aug 25 '18 at 00:12
  • 1
    They are different keywords that do different things, all the documentation for `let` explains clearly why it was introduced as an alternative to `var`. [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) is an excellent resource for learning the ins and outs of JavaScript. – user229044 Aug 25 '18 at 00:16

0 Answers0