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 Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Create a for Loop

i++ is in the For statement so it adds 1 when loop starts. Therefore right answer should be for(i<3;i<157;i++). Mistake?

I learnt Turbo Pascal in a school and teacher told me that i++ is in the statement and it adds 1 to the counter at the beggining of the For loop. Is it only for JavaScript? So For(i<0;i<3;i++) is not equal to var i=0; while(i<3){i++;}. What is my mistake?

script.js

2 Answers

Matthew Long
Matthew Long
28,407 Points

This is incorrect syntax, for JavaScript. You're not setting an initial value. The initial value is set by i = 4. This is the "initial expression". Then you set the max value of i with i < 157 or i <= 156. This is the "condition". Lastly, you increment i with either i++ or i += 1, these do the same thing. This is the "increment expression".

for (var i=4; i <= 156; i++) {
  // body of loop
}

So it''s the same as:

var i=4;
while (i<=156) {
  i++;
}
Matthew Long
Matthew Long
28,407 Points

Sure. There is almost always more than one way to create a loop, or anything for that matter. With the while loop though I see a lot of people increment i first thing in the body of the loop. The results of this are often unexpected, because you're basically skipping the initial value. The challenge associated with this question will only accept the for loop.