Javascript For Loop

Hello Happy One ...

How's your smile doing?

In this tutorial we'll be looking at the For Loop. In programming, loops are a way to iterate over a given block of code. Every language has iteration methods (or loops). There are many variations of these loops, there are While loops, Do-While loops, and our infamous For loop. There are other variations of these three, but these are the basics for Javascript.

The For Loop offers control over the beginning and the ending of an iteration. We have a block of code, we run the code starting from zero as many times as we want until the limit.

Take note of this line of code ...

<?php 
    for (initiationStatement; checkIfLimitWasReached; incrementIteration ) {
        // Block of code to execute over and over
    }
?>

Note that we choose the iteration value and the beginning of the iteration. For a simple for loop, please look at the following example:

<?php 
    for (i = 0; i < 10, i++) {
        // Block of code to be executed
    }
?>

Note that we set the initiation value on this statement :

i = 0;

This is to say that we start our iteration from the value zero and continue with it till we get to the maximum value. Looking at our code the maximum value or our limit is set here :

i < 10;

This means that our limit is the number 10. So the loop starts at 0 runs the block of code inside the loop 10 times before it stops at number 10. Important fact to note here is that we increase the iteration by one every time. That is our count; It goes 0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 and then stops. This here is the code that iterates: i++. Think of i++ as i = i + 1;. They are both increments of one.

Pheew that was a lot for a single seating ... Take a break, eat a slice of warm cabbage, and just scream Loooooopppsss!!!

"Alright, Okay ..." - Denzel Washington

Let's take a few minutes to look at a piece of code that would be inside a for loop. In this one, we're just gonna increase the value of a variable. Let's do it hoommmeezz!

<?php
    var i;
    for (i = 0; i < 10; i++) { 
        echo i.'<br>';
    }
?>

This will print out :

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Do you see Zhang?! The code block inside prints out the counter above. Zero to 9 as we discussed.

Please feel free to play around with the code above, vary the initiation value, the iteration and the limits etc. If you're still uncertain please go over the tutorial a bit, it'll calm you down some more.

"Note that we choose the iteration value, the beginning of the iteration, and the limit."

The Village Geek

In the next tutorial we'll look at a few more For Loop examples. Maybe even get you iterating over objects and arrays.

Play around with the code will ya ... It'll be good decompression for you.

Talk to you next time ...


Cape Town, South Africa

Buy me a coffee ? :) Buy me a coffee :)

Reply to this discussion

Bookmarks

Build
Learn
Coming Soon ...