Reputation: 609
I'm doing a project on CodeAcademy and this part requires a for statement. This is my code:
for(i = 1; i <= 20; i++)
console.log(i);
Basically, I am just wondering, since the second condition "i <=20
" is telling it when to stop repeating the code, why does it not stop straight away. Since 1 is less than 20.
I would think that it should be i = 20
and when i = 20
it stops.
But that doesn't seem to be the case. Which is really confusing me.
Upvotes: 1
Views: 117
Reputation: 30197
because i is incrementing in i++ and it happens until i++ reaches a point where it meets the condition i<=20.
Read it as
keep incrementing i as i++ as long as i <=20
Upvotes: 0
Reputation: 1845
You are confused because you assume the second argument tells it when to stop, this is incorrect, it tells the loop how long to run, so in your case it tells the loop to
run so long as i is less then or equal to 20
See http://www.w3schools.com/js/js_loop_for.asp for more info
Upvotes: 2
Reputation: 51461
To help you reading a for
loop consider always reading them like this:
for( initialization_expression; termination_expression; increment_expression ) {
statements;
}
So to "read" it you can say:
initialization_expression
statements
if termination_expression
is true, else exitincrement_expression
Upvotes: 0
Reputation: 67131
Good little sum up of a for
loop right here:
for ( variable = startvalue; variable < endvalue; variable = variable + increment) {
// code to be executed
}
The first part is a baseline for where the loop counter/index should start.
The middle part is saying while 'variable < endvalue` - keep looping.
variable = variable + increment
written a lot just like variable++;
keeps the loop going forward. as the variable gets incremented. (of course you can increment up/down, it all depends no what you're trying to do).
Upvotes: 0
Reputation: 33143
The middle statement is not telling when to stop the loop, it's telling when it should continue. As long as it evaluates to true, the loop repeats.
Upvotes: 3