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>