Saturday, December 21, 2013

JavaScript Tutorial 7 - For Loops

Like while loops, for loops will run a block a code numerous but times, but with for loops you choose how many times you want to run the block of code. They syntax looks like this...

for (statement1;statement2;statement3)
block of code

Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.

So for example if you wanted to execute a code 5 times you could do something like this...

for (var i = 0; i < 5; i++)

From the example above, you can read:
Statement 1 sets a variable before the loop starts (var i=0).
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has been executed.

So it will output 1,2,3,4,5 then the code will be done.If you wanted to change it to 10 then you could change the i = 0 to i = -5. You could also change the i <5 the i < 10. Lastly you could change the i++ to i+=.5 which changes the amount i increases each time.

This is the very basics of for loops in JavaScript.

No comments:

Post a Comment