2

In the code below when I used var to declare i the boxes I create take the same number but when I change var keyword to use let instead it display correctly. Can any one explain in depth what happened for each situation? Also is there a way to fix it without using let keyword?

<!DOCTYPE html>
<html>
<head>
  <style type="text/css">
    section > div {
      height: 100px;
      width: 100px;
      background-color: red;
      float: left;
      margin: 3px;
      cursor: pointer;
    }
  </style>
  
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script type="text/babel" defer>
    for( var i = 0; i < 45; i++ ){
      var div = document.createElement('div');
      div.onclick = function(){
        alert("you clicked on a box #" + i);
      };
      document.getElementsByTagName('section')[0].appendChild(div);
    }
  </script>
  <title>Let Keyword</title>
</head>
<body>
  <header>
    <h1>Click on a box</h1>
  </header>
  <section></section>
</body>
</html>
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 3
    Specifically this answer has an example: https://stackoverflow.com/a/30479554/5812047 – SamVK Aug 29 '18 at 01:40
  • @SamVK Thanks this helps a lot but I still want to know how I can fix this without using let keyword in the link you post it says: "workaround is to wrap this in an anonymous function and pass i as argument" How I can do that in my case ? –  Aug 29 '18 at 01:55

0 Answers0