JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Create a for Loop

Jim Andrews
Jim Andrews
3,110 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,856 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
3,110 Points

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

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 49,925 Points

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.