I used to think that the scope of a variable declared with var covers the whole scope between the {} but i tried the following example and i would like an explanation please on why when i use 'i' inside the callback function for the onclick event listener the value is not the index of the for loop but the value of i once the for loop is finished.Thank you.
<html>
<head>
</head>
<body>
</body>
<script>
var components = ["1obj", "2obj", "3obj", "4obj", "5obj"];
createDivs(components);
function createDivs(components) {
for (var i = 0; i < components.length; i++) {
var image = document.createElement('div');
image.innerHTML = components[i];
image.index = i;
image.onclick = function () {
console.log(this.index); //gives the real index
console.log(i); //gives the length of components+1
};
document.body.appendChild(image);
}
}
</script>
</html>