Design Development JavaScript

JavaScript 101-#15 – Loops Pt2

Table of Contents

Today, in part 2 of loops we will take a look at “while“ loop and its advanced sibling „do while“ loop. There will be many examples for you to practice these two types of loops and to understand them fully. “while“ and “do while“ are, after “for“ loop last available loops you can use in JavaScript. Even though they work similar like “for“ loop, their syntax is different and there are also other details. Let’s dive in …

In the last part we took a look at „for“ loop and practice on couple of examples. I hope you understood it well because it will help you to grasp today’s topic much faster and easier. As said above, “while” and “for” loop work in similar fashion (after all, they are both loops). However, the syntax of “while” is much different, not to mention “do/while”. Let’ explore both of these two loops more-in-depth.

While

The syntax of “while” is much easier than of “for” loop. It consists only of one part – condition. That’s all. Whole syntax contain “while“ keyword followed by parenthesis with condition and then curly brackets with block of code to be executed if condition is met (if true is returned).

JavaScript:

while ( condition ) {
 code to be executed
}

This aspect – one part syntax – can make it more prone to create infinite loop because you have to include command to break the loop inside the block of code. Let’s try to create some easy example like counting from one to ten and printing the numbers into console. First, we will create variable “int” (shortcut for integer) and set it to one. This value will be then used as condition with “less or equal than” and ten. The result:

JavaScript:

var int = 1;
while (int <=10) {
 // print the value of “int” into console
 console.log(int);
 // increasing the value of “int” variable
 int++;
}

-note: If you switch the order of “console.log()” and “int++” lines, it will first increase the number and then print it out. The first number then will be two and the last eleven. If you delete the “int++” line completely, you will create infinite loop

As a next simple example we will create loop asking the user if he wants to continue or break the loop. This will be done through creating a variable “answer” set to true and “while” loop taking the value of this variable as a condition. Inside the loop we will print some short text into console and ask user, via “confirm()” method if he wishes to continue. The answer will be assigned to “answer” variable as a new value. We will you “confirm()” because it returns either true (OK button) or false (Cancel button), so we can set the condition of “while” loop to true.

JavaScript:

// Creating new variable
var answer = true;
while (answer == true) {
 // Printing text into console
 console.log(“As you wish”);
 // Change the value of “answer” variable
 answer = confirm(“Do you want to continue?”);
}

Let’s combine what we learned in previous part about “for” loop with our today’s subject. Our goal is to create “while” loop nested inside “for” loop (yes, it is possible and easy) that will go through a string of text. “while” loop will print out a line of text every time when letter “o” will be approached by “for” loop. To get this done, we will need to create new variable called “text” with sentence “I want you to code!” as a value. Next step is to create “for” loop. First part – initialization – will consist two new variables – “i” set to 0 and “j” set to “text.length”. Second part – condition – will contain “i < j”. The last part – increment – will contain “i++” (raising “i” variable by 1). As a condition, “while” loop will take current letter (approached by “for” loop) and compare it to “o”. If condition is true, it will print out message “The letter is o!” In order to avoid infinite loop, we will write “break” command on the last line of the “while” loop. What this command does is to break (stop) the loop, statement, program or whatever.

JavaScript:

// creating new variable called “text”
var text = "I want you to code!";

// creating “for” loop
for (var i = 0, j = text.length; i < j; i++) {

 // creating nested “while” loop
 while (text[i] == "o") {
   // printing out the message
   console.log("The letter is o!");
   // breaking the loop
   break;
 }
}

– note: When we use “break” command inside “while” loop, only this loop will be affected. “for” loop will not be influenced.

To make it a bit more complex we can also use an “if” statement. This statement will be nested inside “while” loop and will check if approached letter is either “O” or “o”. It will print “The letter is O!” in the first case and “The letter is o!” otherwise. To make it work properly, we will also need to modify condition of “while” loop by using “||” (or) operator. The result condition will be “text[i] == “O” || text[i] == “o””. After this change, code inside “while” loop (“if” statement) will be executed if letter approached by “for” loop is either “O” or “o”. Variable is set to random text with higher occurrence of letter “o” and “O”.

JavaScript:

// variable with random text
var text = "Oportere aliquando eum ut. Offendit expetenda ne eum. No usu diam tincidunt.";

// for loop
for (var i = 0, j = text.length; i < j; i++) {

 // nested “while” loop
 while (text[i] == "o" || text[i] == "O") {

   // nested “if” statement
   if (text[i] == "O") {
     // if letter is “O” print following message
     console.log("The letter is O!");
   } else {
     // if letter is “o” print this message
     console.log("The letter is o!");
   }
 break;
 }
}

Do/While

In the beginning of this post I mentioned more advanced type of “while” loop called “do/while” loop. This loop only adds keyword “do” followed by block of code to be executed. “do” part should always precede “while loop”, otherwise it will cause an error. The difference between classic “while” loop and this one is that this loop will execute the code block inside “do” part once, before it will checking for the condition (defined inside “while” loop).

Simple example to show how this modification of “while” loop works is to print the value of variable into console when it meets specified condition and also raise the value of variable by 1. The “console.log()” method will be inside block code of “do” part. Condition of “while” loop will be that value inside variable will be lower than 1. We will also add “console.log()” method after the “while” loop to check the value of our variable.

JavaScript:

// variable for condition
var i = 1;

// “do” part
do {
 // printing out value of “i”
 console.log(i); // result - 1
 // raising the value of “i” by 1
 i++;
}

// “while” part
while (i < 1);

// checking the value
console.log(i); // result – 2

As you can see, even though the condition will return false (greater than 1), the value is still once printed into console and value inside variable is raised be 1. Only after this – executing code inside “do” part – will be checked condition specified in “while” part.

Summary

In today’s lesson we took a look at “while” loop and its modified version called “do/while” loop. We also practiced on couple of examples. Two of them included subjects from previous posts like “for” loop and “if” statement. If you didn’t understand anything, please leave a comment or write me a message via links below. I will be happy to help you.

If you liked this article, then please consider subscribing.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.