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 trialSiddharth Pandey
7,280 PointsWhy 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
scribbles
21,173 PointsIn 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
4,566 PointsThe 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).