I am going through a video on the new ECMA 6 JS. I have read the MDN and other web pages on let. But, I don't understand why this code is producing the different results when you use let or var in the for loop. Does it have something to do with the window object?
When var is used, all the console.log messages say 45.
When let is used, the console.log messages are 0 - 44 depending on which box is clicked.
You should be able to copy/paste and run the code below.
<!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://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.29/browser.js"></script>
<script type="text/babel">
for(var i = 0; i < 45; i++){
var div = document.createElement('div');
div.onclick = function() {
console.log("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>