1

I trying to understand some concepts of java script. I wrote this code:

<html>
    <button>Click</button>
    <button>Click</button>
    <button>Click</button>
    <button>Click</button>
    <button>Click</button>
    <script>
        var btn = document.getElementsByTagName("button");
        for(var i = 0; i<5; i++){
         btn[i].onclick = function(){alert(i)}
        }
    </script>
</html>

for each click on each button I will get the same result "5", if I would change the var to let, I will get the correct result. can someone explain why it happened?

John Doe
  • 363
  • 1
  • 5
  • 17
  • See also: [What's the difference between using "let" and "var"?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) – Ouroborus Oct 27 '21 at 18:22

0 Answers0