[X]

Javascript Loop Statements - (Learning Javascript Series)

 

Javascript Looping Statements

Task iteration is one of the most frequently activity that every developer has to perform in most of its projects/applications. Iteration allows to repeat execution of set of statements for some definite time. It enables to avoid writing of same lines of code many times which not only is cumbor some but also waste of time.

Like other languages javascript also provide similar looping statements. Javascript looping statements are more like "C" language as most of the language syntax are derived from there.

So we can now summarise purpose of loop statements:

  • They provide ability to repeat a set of statements for a specific number of times
  • They provide ability to repeat a set of statemens for unknown number of times and/or can be stopped when some criteria is met during program execution

We have four loop statements in javascript.

  1. While
  2. Do-While
  3. For
  4. For-In

Note: There are cases when a loop can end in an infinite loop. An infinite loop is a loop statement that never ends.

While Loop

The while loop evaluates an expression before executing a group of statements. It will execute the statements repeatedly, until the expression no longer evaluates to true.

 

while (expression) {

statements;

manipulate expression, so loop can break after some time;

}//common mistake - never put a ; here

 

 

While loop first evaluates the expression if it is true then enclosed statements are executed, once execution completed it again evaluates for expression to true/false. So the enclosed statements are repeated until expression gets evaluated to false. Here the trick is, to make loop definite, manipulate/alter the expression at the end/beginning of enclosed statement. A while loop evaluates its expression prior to each iteration, which means it is possible that the enclosed statements of the while loop will never be executed.

Example of while loop:

 

<div>
    <script type="text/javascript">
        function printTable() {
            //printing table of 8
            var counter = 1;
            var number = 8;
            var tableString = '';
            while (counter <= 10) {
                tableString += (number * counter) + "\n\r";
                counter++; //or it can also be written as counter=counter+1
            } 
            alert(tableString);
        }
    </script>
    <input type="button" value="Print Table of 8" onclick="printTable()" />
    </div>

We can create an infinite while loop like below:

 

 

while(1) {//(true)

//do some thing or nothing

}

Output:

 

 

Do-While Loop

The do-while loop is similar to the while loop, with one exception that the expression is evaluated after the end of each iteration in a do-while loop. It means the loop is guaranteed to execute at least one time.

 

do {

 statements;

manipulate expression, so loop can break after some time;

} while (expression);//common mistake - never forget to put a ; here

 

 

Example of do-while loop:

<div>
    <script type="text/javascript">
        function printTable() {
            //printing table of 8
            var counter = 1;
            var number = 8;
            var tableString = '';
            do {
                tableString += (number * counter) + "\n\r";
                counter++; //or it can also be written as counter=counter+1
            } while (counter <= 10);
            alert(tableString);
        }
    </script>
    <input type="button" value="Print Table of 8" onclick="printTable()" />
    </div>

Output:

For Loop

A while loop can be rewritten using a for loop. The question between choosing for and while is the convenience and pattern of one's brean which way it feels more comfortable. The one difference one can observe is the option of limiting the counter variable's scope only with in the for loop. If counter variable is declared inside for loop brackets it will not be available for use once out of for loop scope.

for(expression initialization; expression check to a condition; expression increment/decrement){

statements;

}//common mistake - don't put a ; here

Example of for loop:

<div>
    <script type="text/javascript">
        function printTable() {
            //printing table of 8
            var number = 8;
            var tableString = '';
            for(var counter=1; counter<=10; counter++) {
                tableString += (number * counter) + "\n\r";
            }
            alert(tableString);
        }
    </script>
    <input type="button" value="Print Table of 8" onclick="printTable()" />
    </div>

We can create an infinite while loop like below:

 

for(;;) {

//do some thing or nothing

}

 

 

Output:

 

For-in Loop

For in loop is used to iterate through array of objects, it returns the index of object from collection. Then we can use that index value to get content of the object.

 

for(index in object_collection){

//get object from collection using index value

//object_collection[index]

}

Example of for-in loop:

 

<div>
    <script type="text/javascript">
        function ForInLoop() {
            var letters = new Array("A", "B", "C", "D");
            for (var l in letters) {
                document.write(letters[l] + "<br />");
            }
        }
    </script>
    <input type="button" value="For-In Loop Test" onclick="ForInLoop()" />
    </div>

Output:

 

We saw that how loops are used inside javascript programs to perform iteration and what are the various options are available to perform this. We have many looping options in javascript and it is up to one which loop fits best or meets the requirement or matches one's style of coding/thinking pattern.

In next series we will be talking and learning about break and continue statements.

blog comments powered by Disqus

Posts By Month