For, While, Do…While Loop & Continue, Break in JavaScript with Real Life Examples

We use loops in JavaScript when we want to execute a piece of code over & over again. There are three type of loops in JavaScript for loop, while loop & do…while loop.

They work somewhat similar if you look at their behavior. But sometimes developer gets confused which one to use when? In this article, we are going to see some Real Life Examples of JavaScript loops. This will help you to understand when to use them.

For this article, we assume that you already know how to write for, while & do…while statement & their syntax. Please follow the above links if you don’t know.

Note: Loop & Statement words are used interchangeably in this article in context of loops.

For Loop

We use for loop when we want to perform same action repetitively on data. That data can be an array or even properties inside object. For loop ends when it iterates over all the data in the collection.

Let’s see the example of adding tax in a salary amount. Array contains salary. We will try to loop over all the salaries and add tax to them. We will be using for loop to achieve this task.

Example:

‎
const salaries = [5000,4000,20000,6000,84000];

function AddTaxToSalary() {

    for(i = 0; i < salaries.length; i++)
    {
        if(salaries[i] > 10000)
        {
            //Add 10% Tax on Salary

            let salarywithtax = salaries[i] + (salaries[i] * 0.1);
            salaries[i] = salarywithtax;
            console.log("10% Tax Added  :", salaries[i]);
        }
        else
        {
            console.log("No Tax Added  :", salaries[i]);
        }
    }
}

AddTaxToSalary();
‎

We have declared salaries array. Next, we have declared function AddTaxToSalary, which will going to add tax on salary amount.

Inside the function, we have declared for loop to iterate over array of salaries. Inside it we are checking if salary is greater than 10000 then apply tax on it else no tax will be added to a salary.

At the end we are calling AddTaxToSalary function.

Output:

For Loop With Continue

Continue ends the current iteration of the loop and jump to the next iteration. Suppose, we find any irrelevant data while looping which we don’t want to act upon then we can use continue.

  • Continue prevents unnecessary exceptions inside loop which can occur because of inconsistence data.
  • Continue prevents execution of further code if condition does not matched. In the performance point of view, it is really good.

Let’s see the same example of salary with some twist. In this example, we have modified an array little bit. We have added NULL value inside array. We can consider that NULL value as missing salary.

Example:

‎
const salaries = [5000,4000,20000,null,6000,84000];

function AddTaxToSalary() {

    for(i = 0; i < salaries.length; i++)
    {
        if(salaries[i] === null)
        {
            continue;
        }
        if(salaries[i] > 10000)
        {
            //Add 10% Tax on Salary

            let Salarywithtax = salaries[i] + (salaries[i] * 0.1);
            salaries[i] = Salarywithtax;
            console.log("10% Tax Added  :", salaries[i]);
        }
        else
        {
            console.log("No Tax Added  :", salaries[i]);
        }
    }
}

AddTaxToSalary();
‎

Inside for loop we are checking if salary is NULL or not. If salary found to be NULL then just continue with the next iteration.

By using continue in the above example we are preventing execution of next lines of code. We are also preventing any exception to be occurred in the next part of code.

You’ll get same output as above example because NULL has been skipped.

Output:

For Loop With Break

Sometimes you need to terminate for loop. The reason could be missing value or fraudulent data or any unwanted situation in business logic. To accomplish this, we use ‘break‘ keyword.

To demonstrate this we are using ‘Create Invoice‘ example.

Example:

‎
const receipts = [300,150,260,478,null,840];

function CreateInvoice() {
    
    let invoice = 0;

    for(i = 0; i < receipts.length; i++) {
        
        if(receipts[i] === null)
        {
            console.log("Invoice Can't Be Made. Receipt is Missing or Fraudulent");
            invoice = null;
            break;
        }
        invoice += receipts[i];
        
    }
    console.log("Invoice Amount ", invoice);
}

CreateInvoice();
‎

Suppose, we have multiple receipts for product and services we have sold to the customer & now we want to create invoice for the customer.

We have receipts of customers stored in the array receipts. But there is small twist in the array. We have also included NULL value. It means that, one of the receipt is missing. Even if a single receipt is missing, we can’t make a invoice.

We are checking for NULL value in if condition. If it finds NULL value then loop will get terminated by break and invoice value will be set to null with Missing or Fraudulent message.

Output:

Note: If you want to see invoice being created properly then just remove NULL value from array and run the code.

While Loop

There is always a confusion among developers whether to use for loop or while loop. This confusion is more on logical side than technical. Because technically, you could use for or while, there is not much difference.

So, when to use for loop and when to use while loop?

When Data is certain and Action is also certain use for loop.
When Data is certain and Action is uncertain use while loop.

Let’s elaborate above statements.

Example 1:

Suppose, We have 10 children in the class room. Our data is certain. We are going to distribute gifts among them. Distributing gifts is our action. If, we only have 10 gifts then our action will be to distribute gifts equally among children.

Here, our action is certain. We know that we are going to distribute 10 gifts (one per child). Use for loop here. It will simply loop 10 times for each child to distribute gifts.

Example 2:

In the same context, suppose we don’t know how many gifts children will take. Our action is uncertain now.

Our action won’t stop on the basis of children (data) we have, it will stop on the basis of an “stop indication” from children.

That means, we have to perform continues action on data (children) unless and until they say “Enough”. We need to use while statement in this case, we can’t use for loop here. Because we need to stop action on the basis of response from children.

For loop will only act over data (according to size of data) it has.

While loop can also act according to action. It will perform action repetitively on data unless and until it doesn’t get indication to finish action.

Example:

‎
const children = ["Jhon","Alex","Katrina","Jenny", "Mat"];

let distribute_gifts = true;

let start_time = Date.now();

while (distribute_gifts)
{
    let id = Math.floor(Math.random() * children.length);
    console.log("Give Gift to... ", children[id]);

    let current_time = Date.now();

    if((current_time - start_time) > 4)
    {
        distribute_gifts = false;
    }

}
console.log("We Have Enough Gifts Now!...");
‎

As you can see in the above example, we have created children array. We have also declared distribute_gifts variable and set its value to true. While value of distribute_gifts is true, we are going to continue distribute gifts among children.

Note: start_time & current_time we are using just to make distribute_gifts set to false after 4 millisecond. Don’t much emphasize on that part.

Inside while loop, we are fetching random number considering size of array. It is just to distribute gift randomly among children.

In the console log, we are displaying name of child for whom gift being distributed.

After 4 milliseconds, we are setting distribute_gifts to false. “Imagine this as after some time children said we have enough gifts now. We don’t want more gifts“.

When while expression gets false value for distribute_gifts. It will terminate loop & “We Have Enough Gifts Now!…” message will display in console.

Note: In the output, you might see some children get more than one gift or some children get only one gift or some children do not get any gift. Remember, action is depend on children.

Some of them want more gifts, Some of them satisfied with one gift & some of them don’t want any gift. At the end, when no one wants gift anymore, we are ending while loop (stopping gift distribution).

Output:

While Loop With Continue

In this example, we are writing code to check if all servers are on or not. If servers are off, then we are turning them on. We ping all servers one by one in the list and if server is off then we are turning it on and try pinging them again.

Example:

‎
const servers = new Map();
servers.set("S0","On");
servers.set("S1","On");
servers.set("S2","Off");
servers.set("S3","Off");
servers.set("S4","On");

const offservers = Array.of();

let i = 0;
let prefix ="S"
let pingcount = 0;
let ping = true;
let trycount = 0;
 
while(ping) {
    
    if(servers.has(prefix + i)) { 
        if(servers.get(prefix + i)==="On"){
            pingcount++;
            i++;
            continue;
        }
        else {
            offservers.push(prefix + i);
            i++;
            continue;
        }
    }
    
    if(pingcount < servers.size) {

        trycount++;
        
        offservers.forEach(element => {
           servers.set(element,"On");
        });

        console.log("Try " + trycount+ ": " + offservers.join(",") + " Server(s) is/are not Responding. Start Ping Again.");
        i=0;
        pingcount=0;
        offservers.fill(0);
    }
    else if(pingcount === servers.size) {
        
        trycount++;
        ping = false;
        console.log("Try " + trycount + ": All Servers are Responding..");
    }
    
}
‎

In the above example you can see that we have declared map array which contains server name as a key and it’s status as a value.

We are setting variable ping to true. While loop will run over list of servers unless and until all servers will start to respond.

In the initial if condition we are checking if server is available in the Map or not. Then, in the inner if condition we are checking the value of server is on or off.

If “on”, then we are incrementing value of pingcount by one. If value is “off”, then in the else condition we are not incrementing value of pingcount (Because, assume that server is “off” and ping is failed).

We are adding the “off” server name into new array offservers.

Notice that, in both if and else block we have used continue, because we don’t want to execute further code unless and until we loop through all the servers and check their status.

After going through all the servers, we are checking if the ping count is less than server list count or not. If it is less than servers count, that means some servers were in “off” state and they are now inside new array offservers.

We are looping through offservers array and changing their status to “on” inside original Map array.

We are resetting all the initial values. Now, while loop will again check all the servers in the list and it will find all the servers are in “on” state now.

After looping through all the servers it will come down to else-if block and set ping value to false and while loop will end.

Output:

While Loop With Break

We’ll take same children & gift example here but with some changes in logic. What if we only have twenty five gifts available to distribute among children? Or if we don’t have any idea about how many supply of gifts there would be?

Whatever may be the case, we have to keep distributing gifts among the children. But eventually, we have to stop when we will run out of gifts.

Example:

‎
const children = ["Jhon","Alex","Katrina","Jenny", "Mat"];
let distribute_gifts = true;
let gift_availble = 25;

while (distribute_gifts) {
    let id = Math.floor(Math.random() * children.length);
    console.log("Gift to... ", children[id]);
    gift_availble--;

    if(gift_availble < 1) {
        console.log("Gift Supply is Stopped. No more Gifts.");
        break;
    }
}
‎

In the above example, you can see that we have set variable value gift_availble to 25. This value could be dynamic too.

We are keep distributing gifts among the children & at the same time we are decreasing distributed gifts from gift_availble count.

We are use “break” to terminate loop and stop distributing gifts when gift_availble count is 0.

You can see below message in the console log after breaking the loop.

Output:

Do…While Loop

As it says, first do and then check expression. Do…While statement works slightly different from while loop.

First, ‘do‘ block gets execute & if expression is true, then the do…while loop will keep executing ‘do‘ block & when expression is false loop goes inside ‘while‘ block to execute code and end.

Why to use do…while loop?

If you want to perform an action which needs to be executed at least one time then you should use do…while loop.

Because while loop doesn’t guaranty that it will execute at least one time. If expression is false at the first iteration in a while loop then the code will not going to execute inside it.

But in the do…while loop, ‘do‘ block will get execute first. There no expression check needed to execute ‘do‘ block at first iteration. So, it gives you guaranty to execute code at least one time.

In this example, we are writing code to start a bike.

Example:

‎
let kickcount = 1;
let bikenotstarted = true;

do {
    
    if(kickcount === 4) {
        console.log("Kick ", kickcount );
        bikenotstarted = false;
    }
    else {
        console.log("Kick ", kickcount++, "..Not Started Try Again");
    }
}
while(bikenotstarted) {
    console.log("Bike Has Started in " + kickcount + "th Kick" );
}
‎

In the above example, you can see that we have declared two variables kick and bikenotstarted. First one will keep counter of how many times you’re kicking bike to start and latter one keep Boolean value to check whether bike has started or not.

Note: Why we have used do…while here because no matter what, you have to kick bike first to check it has started or not. You can’t check bike started or not without even trying to kick it at first.

So first action is mandatory without any expression or condition.

In the ‘do‘ block, we are checking counter value, if it is equal to 4 then we are starting the bike (setting bikenotstarted value to false).

Unlike while loop, when while in do…while loop gets false expression it execute it’s own block of code and terminates loop. So, it will display message as, “Bike has started in 4th kick“.

Output:

Do…While Loop With Continue

In this example, we have array of numbers. We want those numbers to be copied into blank array. But, we are not using any inbuilt function (copy or clone) to achieve this.

Also, we have to pick random number from existing array & new array should not be containing any duplicate values. Let’s see how to achieve this with do…while loop and continue.

Example:

‎
const a1 = [11,2,7,25,10,4];
let b2 = Array.of();
let Array_Complete = true;

function ReturnRadomValue(values) {
    return values[Math.floor(Math.random() * values.length)];
}

do {
    let val = ReturnRadomValue(a1);

    if(b2.length===a1.length) {
        Array_Complete = false;
    }

    if(b2.includes(val)) {
        continue;
    }
    else {  
        b2.push(val);
    }

}
while (Array_Complete) {
   console.log("a1 array values copied to b2 succesfully. b2 array values:", ...b2);
}
‎

There is an array a1 with some numbers. On the next line we have declared blank array b2. Array_Complete is just a Boolean flag to notify do…while loop when copying gets completed.

There is a ReturnRadomValue function which will pick random value from original array. We’ll add that value to the new array but before that we are checking if value is already added in the new array or not.

If it is added then we are using continue to iterate through next random value.

Loop will continue to execute until array a1 length matches with b2 array length. When both array’s length matches, we will come to know that new array is now filled with all the numbers.

We are setting Array_Complete to false, it will end do…while loop and display new array (b2) values.

Output:

Do…While Loop With Break

In this example, we are fetching two random numbers from the array and we are adding those two numbers. We’ll be keep fetching two random numbers from array and add them unless and until those two numbers make total of 10.

When total is 10, we are using break to terminate loop. We will keep trying again and again till we get total of 10.

Example:

‎
let values_arr = [6,5,'abcd',5,4,7,3];
let istotalnotcreated = true;
let attempt_count = 0;
let totaleof10 = 0;

function ReturnRadomValue(values) {
    return values_arr [Math.floor(Math.random() * values.length)];
}

do {
    let val1 = ReturnRadomValue(values_arr);
    let val2 = ReturnRadomValue(values_arr);
     
    if(!isNaN(val1) && !isNaN(val2))
    {  

        totaleof10 = val1 + val2;
        attempt_count++;

        if(totaleof10 === 10) {
            istotalnotcreated = false;
            console.log("Attempt " + attempt_count + ": Total " + totaleof10);
        }
        else {
            console.log("Attempt " + attempt_count + ": Total " + totaleof10 + ".Try again");
            totaleof10 = 0;
        }
    }
    else {
        attempt_count++;
        console.log("Attempt " + attempt_count + ": Failed to add Numbers. Check Collection of Numbers. It Contains Non-Number Value.");
        break;
    }
}
while(istotalnotcreated) {
    
    if(istotalnotcreated) {
        console.log("Operation Terminated.")
    }
    else {  
    console.log(attempt_count + " Attempt(s) Needed to Create a Total of", totaleof10);
    }
}
‎

We have created values_arr array which contains numbers. Also, we have created ReturnRadomValue function which is going to return random value from array.

We have used do…while loop here because we have to perform addition activity at least one time before we check if total is 10 or not (1st attempt we have to make).

We are retrieving two random numbers and adding them. If total is 10 then we are setting istotalnotcreated to false and it will eventually terminate do…while loop.

If total is not 10, then istotalnotcreated will remain true and do…while loop will continue until it gets total 10.

Before addition of values, you can see that we are checking if both the values are numbers or not. If we found non-number value then in the else condition we are displaying message and terminating do…while loop using break.

Run the above code and keep refreshing html page to see different results all the time. Two types of output given below. You will get somewhat similar kind of output subject to different attempt counts.

Output 1 (Success):

Output 2 (Failed. ‘Break’ Executed):

Conclusion

We hope that above examples will help you to use loops in JavaScript efficiently. Don’t take examples literally. They are just used here to make you ‘think wisely‘ while using loops.

There might be possibility that above examples doesn’t fit as per your business logic or domain you are working in. But it will definitely give you some idea about where to use these different kinds of loops.

Categories js

Leave a Comment