tommo
tommo

Reputation: 609

for statements, <=, javascript

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

Answers (5)

sushil bharwani
sushil bharwani

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

Dani&#235;l Tulp
Dani&#235;l Tulp

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

Strelok
Strelok

Reputation: 51461

To help you reading a for loop consider always reading them like this:

for( initialization_expression; termination_expression; increment_expression ) {
  statements;
}
  • The intialization_expression initializes the loop; it's executed once, as the loop begins.
  • When the termination_expression evaluates to false, the loop terminates.
  • The increment_expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

So to "read" it you can say:

  1. Execute initialization_expression
  2. Execute statements if termination_expression is true, else exit
  3. Execute increment_expression
  4. Go to 2.

Upvotes: 0

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

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

JJJ
JJJ

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

Related Questions