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 Loops, Arrays and Objects Simplify Repetitive Tasks with Loops For Loops

Reid Larson
Reid Larson
12,711 Points

Code wasn't working?

I wasn't getting my code to work. I finally did after removing the ' ; ' after the i+=1 in the for loop. Why would that be the case?

Andrew Jensen-Battaglia
Andrew Jensen-Battaglia
10,051 Points

That's just the syntax rule. In a for loop you have a semicolon after the first and second statement in the ( ) but not the last.

2 Answers

Reid,

Most likely that would cause a syntax error for an unexpected token. Punctuation is very important in control structures like loops. For loops in JS have three statements, one to initialize a variable, one to evaluate a variable and one to change or manipulate a variable on each loop iteration. These statements are separated by semi-colons.

for ( initialize ; evaluate ; manipulate ) {
 ...code code code... 
}

Within a for loop, semi-colons can also indicate when a statement has been omitted. For example if your variable is already initialized prior to the loop.

for (; evaluate ; manipulate ) {
 ...code code code... 
}

Following this logic, a semicolon on the end of the third statement will lead JS to believe that a fourth statement has been omitted, and it will error out because JS only accepts 3 statements in for loops.

I hope this helps!

Reid Larson
Reid Larson
12,711 Points

Ok, that explains it. I assumed that was the case, tried watching the part of the video where it's added but didn't hear that. If it was said elsewhere in the video that was my fault but it may be worth explaining to those who are new? Either way, thanks a lot for the explanation!

I don't remember it being covered in the video, but there's a full explanation here.