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

Jim Andrews
Jim Andrews
5,967 Points

couple question on the 4 - 156 for loop problem.

we need to log all number from 4 to 156 to the consol.

The correct answer is...

for ( var i = 4; i <= 156; i += 1 ) { console.log(i); }

I don't get why this works. If the code goes through the for loop in order, shouldn't it see i as 4, see that it's less than 156, add 1, then log that (being 5, due to the +=1) Wouldn't this start us out at 5 rather than 4? Or does it run the consol.log(i) first before going through the for loop?

Also, why <= 156 instead of just <156? Wouldn't this run up to 156, see that i=156, see that it's <=156, and add 1 to it, logging a 157? If we just use <156, it will read that 155 is there, add 1, and end us at 156, since this not being less than 156 will end the for loop.

script.js
for ( var i = 4; i <= 156; i += 1) { 
  console.log(i); 
}

2 Answers

Antonio De Rose
Antonio De Rose
20,884 Points

did you read the error of your answer.

it does mention that there is a syntax error, all your logic should be correct.

can you check, if your for loop is syntactically correct, there is a very small issue, in the below line

for ( var i = 4; i <= 156; i += 1; )

https://www.w3schools.com/js/js_loop_for.asp

Jim Andrews
Jim Andrews
5,967 Points

@Antonio De Rose I'm sorry, the last ; wasn't in the final answer. You're right.

See the for loop here

The for loop has the following syntax:

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.