Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

gugulethu
gugulethu
6,292 Points

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

gugulethu
gugulethu
6,292 Points

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 :)