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

Siddharth Pandey
Siddharth Pandey
4,069 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,115 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).