ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

JavaScript While Loop and Do While

Updated on August 21, 2019
Sam Shepards profile image

I'm a software developer with a great interest in data analysis and statistics.

When we have a program where we need to repeat certain actions we’ll use some kind of looping construct. There are different kinds of loops and some more implementations of those. In this case we’ll talk about the while loop. The while loop is fairly easy to grasp.

While a certain condition is true, execute the code block / statements inside the while loop statement. As soon as the condition is false we’ll not repeat the execution of the while loop. As we’ll see this is very useful and allows use to do a lot of actions with very little code.

How Does The While Loop Work

We have an expression that evaluates a condition for the while loop. If that condition is equal to true the code block inside the curly braces of the while loop is executed. As long as that condition remains true the body of the while loop will be repeatedly executed. If the condition was false the first time it was evaluated, the while loop would never start and the code inside it would never be executed.

Now how do we exit or terminate the repeated execution? By changing the condition expression from inside the loop, using a break statement or in some cases by returning something.

Basic While Loop Syntax

If you only have one statement in the while loop you don’t have to use curly braces. Most people will always use braces for readability and out of habit. So the best bet is to just use them, even when you only have one statement.

while(condition expression) {
//code block to be repeatedly executed
//when condition expression evaluates to true
}

while(condition expression)
// one statement

While Loop With Count

Here we have a countdown which ends with lift off. We declare and initialize a count before we start the loop. We evaluate the count in the expression. As long as the count is greater than 0 we will execute the code inside the loop.

Inside the loop we print the count value each time and decrement it. We will terminate the looping construct when the count is not greater than 0. Finally we print the lift off.

let count = 10;
   
while (count > 0) {
    console.log(count);
    count--;
}
   
console.log('lift off');

While Loop With Boolean

Here we set myBool to true and use that for the condition expression. As long as myBool is true the code inside the loop will be executed. Inside the loop we will generate a random floating point number between 0 and 10 each iteration. If the random number is greater than 8 we set myBool to false and terminate the loop.

Something like this can be useful, but we have to keep in mind that we should exit the loop at some point.

let myBool = true;
   
while (myBool) {
    let randomNum = Math.random() * 10;
    console.log(randomNum)
    if (randomNum > 8) {
      myBool = false;
    }
}

Danger Infinite While Loop

In this example we will see that it can cause problems if we are not sure the loop will end. In this case I’ve put the random number generation outside the while loop, so it will only generate the number once. In the previous code example we get a new random number with each iteration.

Which means if the number we generate is not greater than 8 the first time we enter the loop we will not be able to exit the loop like the previous example. We will never enter the code block in the if statement and myBool will never be set to false. We’ll have around 4 chances in 5 we will end up in an infinite loop.

An infinite loop often makes a browser or program crash or at least it will be stuck in the loop until we kill the process. Just take a look at the code below. If you don’t want to crash your browser or be stuck in the loop then don’t try the code.

let myBool = true;
let randomNum = Math.random() * 10;
   
while (myBool) {
    console.log(randomNum)
    if (randomNum > 8) {
      myBool = false;
    }
}

Using Return To Exit Loop

We can also exit a while loop by using a return statement. Of course we can only do this if the while loop is part of a function or method. There are also some concerns about this being a clean coding practice or not. Some people prefer to see only one return statement inside a function.

Too many returns can make it more difficult to figure out what the function ends up doing. But in simple cases it’s still often used so I leave that discussion for another topic and just show how it would work.

Here we have a function that will search for the string ‘Rabbit’ inside an array. I could have used the index in the condition of the while loop, but I wanted to show a boolean literal is also possible. Keep in mind that if we would not find a ‘Rabbit’ string in the array this would never terminate and we would have an infinite loop.

This can be bad coding, because now I presume that the caller of my function knows it should only send me an array that has a ‘Rabbit’. Here I’m the maker of the function and the user so it’s not that big a deal, but in many cases it could be fatal to make such assumptions.

When we find the ‘Rabbit’ we return its index in the array and the while loop terminates. You could do things like add checks to see if it is last element of the array, return something else if the ‘Rabbit’ has no been found, -1 for example. But the more options and possible exits you would create the more dirty it can become.

Use this with caution, be sure on what your input can be and how and when you are going to terminate the loop.

function searchRabbit(arr) {
   
let index = 0;
    while(true) {
        if(arr[i] === 'Rabbit') {
            return i;
        }
        i++
    }
}
let rabbitIndex = searchRabbit(['Dog', 'Horse', 'Rabbit', 'Bird', 'Snake']);
console.log('We will find the rabbit at ' + rabbitIndex);

Using Return To Exit Loop

Here we use a break to exit the loop early. We could accomplish something similar by using x > 250 as the condition expression of the while loop. But this example is purely to illustrate the use of break and not what you should use. As soon as the condition in the if-statement is true, the value of x will be logged to the console and we will break out of the while loop.

let x = 5;
   
while(true) {
    x = x + x;
    if (x > 250) {
        console.log(x);
        break;
    }
}

JavaScript Do While Loop

The while loop is a basic construct in JavaScript to repeat certain actions as long as a certain condition evaluates to true. The looping is terminated when the condition evaluates to false right before the next iteration, we break out of it or when we exit it with a return statement (used in functions).

Whereas the normal while loop always evaluates the condition before entering the loop, the do…while condition is not evaluated the first time we enter the body. The code block or statement inside the do…while is executed at least once. The condition for repeating the loop is evaluated after executing statement(s) inside the curly braces the first pass through.

As long as the condition is true both do…while and a regular while loop will repeat the statement or code block inside the body.

How DoesThe Do While Loop Work?

When we enter the do…while the body, a statement or the code block inside the curly braces, is executed. Next the condition expression will be evaluated, if this is true then the next iteration starts. If it is false the loop terminates. The benefit of this loop over the regular while loop is when you want to be sure the code block is executed at least once.

Do…While Syntax

If we have just one statement we don’t need the curly braces. As a good practice and for readability many people always write the curly brace.

Do
// a statement
while (condition expression);

When we have multiple statements inside the body, we have a code block. A code block is encapsulated by curly braces, we need the braces.

Do {
// code block,
//multiple statements to execute
} while (condition expression);

Do…While Execute Once

The first do…while construct has just one statement so the curly braces are not obligatory. I made this example use a false condition to show what really separates this from a regular while loop. Here we see that the string ‘Lets print a message is’ will be printed once. After printing the message the condition will be evaluated and results in false. The do…while will not repeat.

The second example is similar but with a counter and the use of curly braces, because the body is now more than one statement. The condition will also evaluate to false, but because the code block is execute one time before the condition, value of x is printed. Next we increment the x inside the body so when we get to the condition the x will be equal to 5 and the condition will evaluate to false.

// just on statement inside do...while
let myBool = false;
do
    console.log("Lets print a message");
while (myBool);
   
// a code block so need curly braces
let x = 4;
do {
    console.log('x = ' + x);
    x++;
} while (x < 5);

Do…While Multiple Iterations Example

Will print from 0 to 9 before it terminates. This do…while will increment each iteration right after it prints the value of x.

let x = 0;
do {
    console.log('x = ' + x);
    x++;
} while (x < 10);

© 2019 Sam Shepards

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)