CodingBison

Often an application needs to run in a loop to execute a task repetitively. As an example, if we have an array that holds a series of user input and if we are looking for a specific user input, then we can run in a loop and keep iterating until we find an input that matches the specific input.

For such looping-based tasks, JavaScript provides four different constructs: (1) while loop (2) do-while loop, (3) for loop, and (4) for/in loop.

Conceptually, a loop depends upon a specified condition to determine whether to continue further or to terminate/stop; the condition can be a simple variable or an expression. Typically, a loop would periodically check if the condition is true and it will run as long as the condition is true.

Needless to say, for the above scheme to work, the loop variable or the loop expression that form the condition, must also change as the loop progresses; if they do not, then the loop would simply run forever! It is not that there are no programs that require a loop to run forever; on the contrary, there are many. However, a vast majority of programs would in fact require the loop to stop at some point. For such programs, we can articulate the scheme of condition check into three stages: loop-initialization (where the loop variable or the expression is initialized), loop-increment (where the loop variable or the expression is changed), and loop-condition (where we check if the condition is still true).

Before we move on, let us provide a simple representation of these loops. As shown below, a while loop runs as long as the specified condition ("loop-condition") is true. Typically, during each round, we need to update the loop-condition so that the loop can terminate after some time. The do-while variant also has a similar format, except that the while sits at the end of the loop block (don't forget the semicolon at the end of the while!). The third variant is the "for" loop. This method cleanly tucks all the three tasks of looping in the beginning expression itself: loop-initialization, loop-increment, and loop-condition. The last variant, the "for/in" method traverses enumerable properties of objects. At each pass, we assign the next property of the object to the variable element.

 // Format of a while loop 
 while (loop-condition) {
     Execute some statements
 } 

 // Format of a do-while loop 
 do { 
     Execute some statements
 } while (loop-condition);

 // Format of a for loop 
 for (loop-initialization; loop-increment; loop-condition) {
     Execute some statements
 } 

 // Format of a for/in loop; elements are object's properties. 
 for (elements in object) {
     Execute some statements
 } 

It is worth noting the difference between while and do-while methods. With the do-while method, the loop block is executed at least once. This happens because even if the while condition is false, the program must run starting from "do" till the point where it reaches the "while" condition. Thus, for cases, where we need to run the loop for the first round, irrespective of the condition, we should consider the do-while method.

Now, let us go through a simple program (provided below) to demonstrate the above looping variants of while, do-while, for, and for/in. For the first three variants, the condition is: "i < arrMagic.length". And, with each iteration, we increment the value of "i" so that after we have counted all the elements of the array, these loops terminate. For "for/in" loop, all the elements present in object are automatically taken into account and so, we do need to explicitly check if the length is reached. Another interesting aspect of the "for/in" loop is that with arrays, the properties are array indexes ("0", "1", "2", and so on) and so the variable element actually holds array indexes.

 <!doctype html>
 <html>
 <div id="idDiv"> </div>

 <script type="text/javascript"> 
 // Get a handle of the div element. 
 var elem = document.getElementById("idDiv");

 // Define arrMagic with some initial values.
 var arrMagic = ["Wise Dragon", "Young wizard", "Mischievous Goblin"];

 // Let us print the elements using a while loop. 
 elem.innerHTML += "Printing array using a while loop: <br>";
 var i = 0;
 while (i < arrMagic.length) {
     elem.innerHTML += "[index: " + i + "] value: ";
     elem.innerHTML += arrMagic[i] + "<br>";
     i++;
 }

 // Let us print the elements using a do-while loop.
 elem.innerHTML += "<br>Printing array using a do-while loop: <br>";
 i = 0;
 do {
     elem.innerHTML += "[index: " + i + "] value: ";
     elem.innerHTML += arrMagic[i] + "<br>";
     i++;
 } while (i < arrMagic.length);

 // Let us print the elements using a for loop.
 elem.innerHTML += "<br>Printing array using a for loop: <br>";
 for (i=0; i < arrMagic.length; i++) {
     elem.innerHTML += "[index: " + i + "] value: ";
     elem.innerHTML += arrMagic[i] + "<br>";
 }

 // Let us print the elements using a for-in loop.
 elem.innerHTML += "<br>Printing array using a for-in loop: <br>";
 for (var element in arrMagic) {
     // With for-in loop, the elements of an array are its indexes!
     elem.innerHTML += "[index: " + element + "] value: ";
     elem.innerHTML += arrMagic[element] + "<br>";
 }
 </script>
 </html>

When we run the above example (save in a file, let us say, "basic_loop.html", and point the browser to that file), the output shows that all four methods identically print the array elements.



Figure: Loop Variants

Selective Looping: Continue and Break

Running in a loop and terminating when the specified condition becomes false is not always enough. Sometimes, the logic might need to be more selective! A program may wish to skip some of the records while iterating through all the records. Or, it may wish to break out of the loop immediately once it finds a certain record and not even bother to check the remaining ones.

To handle such cases, JavaScript provides two loop-based keywords: continue and break. The keyword continue allows a program to skip the current record and continue with the next one. The keyword break allows a program to break out of the loop as soon as it finds a specified record. Thus, we can use "continue" to eliminate records and use "break" to select records.

Let us understand keywords continue and break a little more.

Suppose we need to print a list of user input and while printing, we need to skip some of the list-items based on a specific criteria. We can do so with "continue" -- whenever an item does not meet the specified criteria, we can skip that item and continue to the next one. Thus, this allows us to skip all the items that do not meet the criteria.

While "continue" allows us to eliminate items that do not meet a criteria, "break" allows us to select the very first item that meets the criteria and exit. We can use the "break" to look for a specific input and the moment we find it, we can exit out of the loop without even bothering to analyze the remaining items.

Let us modify the previous example to see usage of these keywords. For the sake of simplicity, we use a "for" loop; these keywords apply equally to remaining loop variants as well, including the for/in variant. This example processes a list of user-input that holds various magical beings. It uses "continue" to eliminate all those beings that do not fly and uses "break" to select the first magical being that can spit fire.

 <!doctype html>
 <html>
 <div id="idDiv"> </div>

 <script type="text/javascript"> 
 // Get a handle of the div element. 
 var elem = document.getElementById("idDiv");

 // Define arrMagic with some initial values.
 var arrMagic = ["Magical Elves","Wise Dragon","Young Wizard","Dark Lord","Strong Griffin"];

 // Usage of "continue": find all beings that can fly!
 elem.innerHTML += "Let us skip certain records while printing <br>";
 for (i=0; i < arrMagic.length; i++) {
     if ((arrMagic[i] != "Wise Dragon") && (arrMagic[i] != "Strong Griffin")) {
         elem.innerHTML += "[index: " + i + "] Searching... <br>";
         continue;
     } 
     elem.innerHTML += "[index: " + i + "] Found someone! ";
     elem.innerHTML += arrMagic[i] + "<br>";
 }

 // Usage of "break": find the being that can spit fire! 
 elem.innerHTML += "<br>Let us find a specific record <br>";
 for (i=0; i < arrMagic.length; i++) {
     if (arrMagic[i] == "Wise Dragon") { 
         elem.innerHTML += "[index: " + i + "] Found someone! ";
         elem.innerHTML += arrMagic[i] + "<br>";
         break;
     } else {
         elem.innerHTML += "[index: " + i + "] Searching...<br>";
     }
 }
 </script>
 </html>

Here is the browser output, if we run the above program (save it as a file and point the browser to it). We can see that with "continue", the loop iterates over all array elements to find all magical beings that can fly. On the other hand, with "break", it immediately terminates when it finds a fire-spitting magical being.

 Let us skip certain records while printing 
 [index: 0] Searching... 
 [index: 1] Found someone! Wise Dragon
 [index: 2] Searching... 
 [index: 3] Searching... 
 [index: 4] Found someone! Strong Griffin

 Let us find a specific record 
 [index: 0] Searching... 
 [index: 1] Found someone! Wise Dragon




comments powered by Disqus