JavaScript JavaScript and the DOM Responding to User Interaction Listening for Events with addEventListener()

var vs let in the for loop explanation

Hi I need an explanation for the following.

When I run the code below, I get: TypeError ListItems[g] is undefined

const listItems = document.getElementsByTagName("li");

for (let g = 0; g < listItems.length; g++ ) {

listItems[g].addEventListener("mouseover", () => { listItems[g].textContent = listItems[g].textContent.toUpperCase(); });

listItems[g].addEventListener("mouseout", () => { listItems[g].textContent = listItems[g].textContent.toLowerCase(); });

}

And when I use this code it runs well:

const listItems = document.getElementsByTagName("li");

for (var g = 0; g < listItems.length; g++ ) {

listItems[g].addEventListener("mouseover", () => { listItems[g].textContent = listItems[g].textContent.toUpperCase(); });

listItems[g].addEventListener("mouseout", () => { listItems[g].textContent = listItems[g].textContent.toLowerCase(); });

}

The difference here is that the first uses 'var' in the for loop and the sencond uses 'let'.

I want to understand why that makes a difference. My understanding is that 'let' limits the variable to the block, whereas var is global and that with complicated programs 'let' is safer to limit the scope of the variable. In this context, why does it matter?

Thanks

2 Answers

Annet de Boer
Annet de Boer
900 Points

If you literally get the error "TypeError ListItems[g] is undefined" then it's a matter of capital L versus lowercase L (ListItems is not the same as listItems) although I don't see it in your code here.

For about 'let' versus 'var'; it's not supposed to give you this error. But a nice explanation with examples can be found here http://stackoverflow.com/a/11444416

I've been an idiot. I did not not save the file after fixing that typo so I mistakenly attributed the error to 'var'.

Also, I can see my understanding about the difference between the two is off. Thanks for the clarifying link.

Annet de Boer
Annet de Boer
900 Points

Nice, no problem, great that you've got it working now :)