0

I have a simple JavaSciript function:

<!DOCTYPE html>
<html>
  <head>
    <title>ECMAScript</title>
    <style>
      #box {
        display: flex;
        justify-content: space-around;
      }
      #box > div {
        height: 5em;
        width: 5em;
        background-color: purple;
      }
    </style>
  </head>
  <body>
    <h1>Let</h1>
    <div id="box"></div>
    <script type="text/javascript">
      var div;
      var box = document.getElementById("box");

      for (var i = 0; i < 5; i++) {
        div = document.createElement("div");
        div.onclick = function () {
          alert("This is box # " + i);
        };
        box.appendChild(div);
      }
    </script>
  </body>
</html>

If you copy paste this code in a text editor and save it as .html, a simple webpage with 5 purple boxes show up. When I click on any box I get the message:

This is box# 5

I am not sure why.

I understand the difference between let and diff and changing the var i to let i solves the issue.

for (var i = 0; i < 5; i++) {

to this line

for (let i = 0; i < 5; i++) {

I would love to understand why this happens.

Pawan
  • 99
  • 1
  • 13

0 Answers0