There are 4 kinds of loops. In this tutorial, we’ll be talking about the for loop. The for loop is very simple and effective to use.
Creating A For Loop
Clear your script and update your code to this.
var total = 0;
for (var i = 0; i < 10; i++)
total += 10;
alert( total );
for( INITIALIZER; CONDITION; INCREMENT )
The first part is the initializer. The initializer gives you the opportunity to create a variable. The variable created here is usually the starting point for your loop. You’ll see what I mean in a moment.
The next part is the condition. To prevent your loop from running forever, this condition must be true in order for the loop to continue running. The rules that apply to the conditions in if-else statements apply here.
The third part is the increment or decrement. We’ll discuss this part in more detail a little later in this tutorial. The final part is the code that you want executed each time this loop runs. The first 3 parts are separated by semi-colons and are typed inside the parenthesis.
If you take a look at our for loop, notice that initializer is a variable called i with the value of 0. Usually your initializer will start at 0 or a number that goes down. Our condition is i < 10. i is equal to 0 so this will return true because 0 is always less than 10.
Our loop will run endlessly because our condition is always true. In order to change this, we use our increment to increase the value of i. We never discussed what increments and decrements are.
Increments & Decrements
By incrementing a value, you’re adding 1 to it. A shortcut to do this is the use the increment operator which is two plus signs ( ++ ). To decrement a value, you use 2 minus signs ( — ).
Our for loop runs the code inside the curly brackets. Here are a couple of things you should know about for loops.
- The initializer only runs once and is the first thing to run.
- Even though the increment/decrement part is coded before the block of code, it actually runs last.
- The order in which a loop runs is initializer, condition, block of code, increment, condition, block of code, increment, condition, etc…
The increment allows us to move i up once so our condition eventually returns false and the loop stops running. Inside our loop, the total has 10 added to it’s original value. We then alert the final value of total in our script. You should get 100. You should know that code after our loop won’t run until the loop is completely finished running.
For Loops are easy to construct. You shouldn’t allow your loops to run endlessly or else you’ll end up freezing your browser. We’ll be creating for loops in future tutorials.