Introduction To JavaScript Loops: Do-While, For, For-In Loops

When you interact with a web page, mobile application, or an online game, there’s a good chance that it was built with JavaScript. If you are looking to learn how to code with it, you’ve come to the right place! Here, we will go over one of the most commonly used tools in this programming languageJavaScript loops.

Loops are programming constructs that facilitate the execution of a set of instructions of code repeatedly, as long as a certain condition is met.  

This article focuses on the different types of JavaScript loops, and will cover the following topics: 

  1. What are JavaScript loops?
  2. The for loop
  3. The for-in loop
  4. The for-of loop
  5. The while loop
  6. The do-while loop

First, we’ll go through the introduction of a loop, including their classifications. 

What are JavaScript Loops?

A loop is a programming construct that repeatedly executes a piece of code. Loops are simple, yet extremely powerful. 

Loops are broadly divided into two categories: 

  1. Entry Controlled Loops 
  2. Exit Controlled Loops 

loops

Types of loops - JavaScript loops

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

Entry Control Loops 

These control the entry to the loop. They check for a condition and the control is transferred inside the loop if, and only if, the condition is true. These loops are used when checking for a condition before execution is mandatory. Examples include for and while loops

Exit Control Loops

An exit control loop controls the exit. The exit control loop checks the condition for an exit. If the given condition for exit is true, control will exit from the loop body, or else control will enter again into the loop. An example of an exit controlled loop is a do-while loop.

The For Loop

javascript-loop

  JavaScript for loops

The flowchart above shows the simple JavaScript for loop logic. As mentioned earlier, a for loop is an entry controlled loop and tests the condition before entering the loop. 

loop-syntax

    JavaScript for loops syntax

Consider the following block of code:

<script>

let n 

document.write("The numbers are: " + "<br>");

for(n=0;n<10;n++)

document.write(n + " ")

</script>

The output of the above code will be as follows:

javascript-tutorial

      JavaScript For loops

In the above example, statement one sets the variable n to zero before the loop starts. Statement two sets the condition to be less than ten. Statement three increases the value of the variable by one after every loop. 

When it comes to statement one in the for loop, JavaScript enables the initialization of multiple variables where the looping variable is initialized. 

Consider the code snippet shown below:

<script>

let n = [2,4,6,8,10,12,14] 

for(i=0,len=n.length,sum=0; i<len; i++)

sum += n[i]

document.write("The sum is " + sum)

</script>

This example shows the creation of array n. The variables i and sum are initialized to zero and len is initialized to the length of the array. Within the loop, we will be performing the sum action. 

The output of the above code is shown as: 

sum-56

JavaScript For loops 

The For...In Loop

The for...in in JavaScript loop is used to iterate over the properties of an object. Consider the following code: 

<script>

var personal_info = {fname: "Jason", lname: "Gil", age:25}

var x 

for(x in personal_info)

document.write(personal_info[x] + "<br>")

</script>

In this example, we’ve created an object with the name personal_info. The properties include the first name, last name, and the age of a person. The code above will print the values of these properties.

jason-gil-25

For… in loops 

To print the property along with its value, you can replace the output code with the following: 

document.write(x + ' : ' + personal_info[x] +  "<br>")

For...in loop 

The For...Of Loop

The for...of statement creates a loop iterating over objects. This gives users the ability to loop over data structures, such as arrays, strings, NodeLists, and maps.

General syntax: 

for (variable of iterable) { statement }

Variables acquire different properties on every iteration. 

Iterable is the object whose properties are iterated over. For example:

  • Jason
  • Jill
  • 25

Consider the following piece of code: 

<script>

var array1 = ['Jason', 'Gil', 25];

for (var element of array1) 

console.log(element);

</script>

In this example, element is the variable, and the array “array1” is iterable. 

The output of the code above is as follows:

elementsconsole

for...of loop

The While Loop

while-loop

    While loop flowchart - JavaScript loops

A while loop refers to the entry controlled loop that checks the condition before transferring the control to the loop. It iterates over and executes the piece of code, as long as the condition is true.

General syntax: 

while (variable < endingCondition)

The variable is the value that will change. The endingCondition is the maximum value a variable can reach. 

Let’s take a look at the following code:

<script>

let x = 1;

document.write("The values are "+ "<br>")

while(x<=5){
document.write(x + " ")

            x++;

        }

</script>

As you can see, the condition for “x” is checked first and only printed if it is less than five. The output will then be as follows:

/values-are

JavaScript While loop 

The Do-While Loop

This do-while loop is an exit controlled loop that checks the condition at the end of the code. This loop ensures that the code is executed at least once.


do-while-loop.

    Do-while loop flowchart 

Consider the following piece of code:

<script>

let x=15;

document.write("The numbers are: " + "<br>")

do{

document.write(x  + " ")

x++

  }

while(x<10)

</script>

Here, the value of x is initialized to 15. When the control enters the loop, the value is printed and incremented. However, when the condition is checked, it fails and as a result, terminates. 

The output is: 

            do-while loop 

Now, if the value of x is initialized to five instead of 15, the output will be completely different. The condition will hold true until the value reaches 10, and then the output will be the following: 

numers-56789

        do-while loop

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Next Steps 

We hope that this JavaScript loops introductory article was helpful, whether you’re brand new to JavaScript or have some experience with this widely used scripting language.

If you’re looking to learn more about JavaScript on a professional level and advance your career, then a course certificate is essential. Simplilearn’s JavaScript Certification Training course helps students master the JavaScript programming language in an all-inclusive training program that includes complete JavaScript fundamentals, jQuery, Ajax, and more. Students will also apply their skills through a capstone project that includes building a real-time chat application.

If you’d like to know more, please comment below. Our experts will get back to you shortly. 

About the Author

Chinmayee DeshpandeChinmayee Deshpande

Chinmayee is a Research Analyst and a passionate writer. Being a technology enthusiast, her thorough knowledge about the subject helps her develop structured content and deliver accordingly.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.