Trying to grasp the differences between the two and I am experimenting with different examples to ensure I understand properly.
I have already looked at this question on Stack Overflow: What's the difference between using "let" and "var" to declare a variable?
It seemed to make sense until I stumbled across this code segment: http://jsbin.com/xepovisesi/edit?html,output
const buttons = document.getElementsByTagName("button");
for(var i = 0; i < buttons.length; i++) {
const button = buttons[i];
button.addEventListener("click", function() {
alert("Button " + i + " Pressed");
});
}
<button />
<button />
<button />
<button />
If you change the first for loop statement to a let, the functionality works as expected... It alerts which button was pressed. However var just alerts "Button 10 was pressed" every time. Why is it doing this?
Thanks, James.