Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Siddharth Pandey
Siddharth Pandey
7,280 Points

Why doesn't this work

How come when I try to run over a list of elements, the loop: for(i = 0; i < listItems.length; i++) { In here are the functions, they are correct, the same as the ones in the video } However, I get a syntax error and the loop doesn't run. Yet when I do this: for(let i = 0; i < listItems.length; i++) {} that works. Why is this?

2 Answers

In JavaScript you need to declare a variable before you can use it. One of the ways to do this is to use the let keyword. Like so:

let i = 0;

This is pretty much telling the computer to set up a variable called i and set its value equal to 0.

In your first loop:

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

You are setting i equal to zero, this is telling the computer to set the value of the variable with the name of i equal to 0, but there is no variable with the name of i since it hasn't been declared/created yet, therefore the loop doesn't work.

In the correct example:

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

The computer creates the variable i first and then sets it to 0.

Zac Anderson
Zac Anderson
4,566 Points

The code did not run because in the loop: for(i = 0; i < listItems.length; i++), 'i' was not declared a variable. When you add the keyword 'let' or 'var', the program understands that it is a variable and then ran the loop as expected (You only need a keyword if the counter variable has not already been declared).