-1

The code below is not my code. Can someone explain it? I don't know much JavaScript so I dont really understand it. I think thats why I dont understand how using let in a for loop makes the i variable distinct for each cycle through the loop? Using var should do the same.

<html>
  <head>
    <title>buttons - let and Const</title>
  </head>
  <body>
    <h1>Buttons</h1>
    <button>Button 0</button>
    <button>Button 1</button>
    <button>Button 2</button>
    <button>Button 3</button>
    <button>Button 4</button>
    <button>Button 5</button>
    <button>Button 6</button>
    <button>Button 7</button>
    <button>Button 8</button>
    <button>Button 9</button>
    <script>
      const buttons = document.getElementsByTagName("button");
      
      for(let i = 0; i < buttons.length; i++) {
          const button = buttons[i];
          button.addEventListener("click", function() {
              alert("Button " + i + " Pressed");
          }); 
      }
    </script>
  </body>
</html>
  • 4
    Possible duplicate of ['let' vs 'var' in javascript for loops, does it mean that all the for loops using the 'var i =0' should actually be 'let i =0' instead?](https://stackoverflow.com/questions/32313961/let-vs-var-in-javascript-for-loops-does-it-mean-that-all-the-for-loops-usin) and [What's the difference between using “let” and “var”?](https://stackoverflow.com/questions/762011) – adiga Apr 01 '19 at 20:23
  • 1
    *"Using var should do the same"* ... No. It doesn't – charlietfl Apr 01 '19 at 20:25
  • This is the opposite of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/q/750486/9029328) – AuxTaco Apr 01 '19 at 20:28
  • @charlietfl i feel that i should because i is different each time through the loop too because i is getting incremented by one. – HeavensGate666 Apr 01 '19 at 20:45
  • Yes it does increment using both var and let....however if you use `var` it will be at it's maximum when the event occurs whereas using let is block scoped and `i` will maintain it's value when event occurs – charlietfl Apr 01 '19 at 20:46
  • @charlietfl yes i know this i am just confused because i dont understand the code. So i know the loop runs no matter what. This part ( ` button.addEventListener("click", function() { alert("Button " + i + " Pressed");` ) is ran in the loop but what if i click on a button when the loop is over? – HeavensGate666 Apr 01 '19 at 20:54
  • The loop will definitely be over when the button event occurs. It will run in a few 1000ths of a second – charlietfl Apr 01 '19 at 20:55
  • @charlietfl so why does the code inside the loop still run? – HeavensGate666 Apr 01 '19 at 20:56
  • It runs and creates multiple event listeners and is done faster than you can blink. The difference between `let` and `var` appears when try to access `i` inside the event handler when it fires minutes later.....in computer time, an eternity after loop completes – charlietfl Apr 01 '19 at 20:57
  • @charlietfl ok i get the code now. I dont know any programmers here in oslo so i dont have anyone to ask my beginner level questions so thank you very much charlie! – HeavensGate666 Apr 01 '19 at 21:01

2 Answers2

2

The key difference between let and var in a for loop can only be seen if you try to access the variable asynchronously. Using var the variable gets allocated once, and on every iteration that value will be changed. Using let the variable will be allocated in a different memory location at each iteration, and the value of the previous iteration will be copied in the new location. If you access it asynchronously it will refer to that memory location.

 for(var i = 0, test = 0; i < 10; i++) {
   // test: 1, 2, 3 -> the same value gets mutated
   // i: 10, 10, 10-> the same value, the loop already finished
   setTimeout(() => console.log("i", i, "test 1", ++test)); 
 }

for(let i = 0, test = 0; i < 10; i++) {
  // test: 1, 1, 1 -> a new "test" got allocated on each iteration
  // i: 0, 1, 2 -> kept at every iteration
  setTimeout(() => console.log("i", i, "test 2", ++test));
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • can you comment a link to where you got this information please? I want to read more about it – HeavensGate666 Apr 01 '19 at 21:23
  • Well the definite answer is always the [spec](https://www.ecma-international.org/publications/standards/Ecma-262.htm), but [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) is way more readable – Jonas Wilms Apr 01 '19 at 21:39
1

The let keyword is used to declare variables with a limited scope.

Here is a great article about the differences between let and var.

From the article :

let gives you the privilege to declare variables that are limited in scope to the block, statement of expression, unlike var.

In your example i will only be available in the scope of the for loop.

Jimmy Leahy
  • 566
  • 3
  • 14
  • I get the difference between them im just confused because i read like ten minutes ago that "in a for loop the i variable is different each time through the loop" which is weird to me because i feel that var is different each time through the loop to because i is getting incremented by one. – HeavensGate666 Apr 01 '19 at 20:43