For, While and Do While LOOP in JavaScript (with Example)

In this tutorial, we will learn-

How to use Loop?

Loops are useful when you have to execute the same lines of code repeatedly, for a specific number of times or as long as a specific condition is true. Suppose you want to type a ‘Hello’ message 100 times in your webpage. Of course, you will have to copy and paste the same line 100 times. Instead, if you use loops, you can complete this task in just 3 or 4 lines.

How to use Loops in Javascript

Different Types of Loops

There are mainly four types of loops in JavaScript.

  1. for loop
  2. for/in a loop (explained later)
  3. while loop
  4. do…while loop

for loop

Syntax:

for(statement1; statement2; statment3)

{

lines of code to be executed

}
  1. The statement1 is executed first even before executing the looping code. So, this statement is normally used to assign values to variables that will be used inside the loop.
  2. The statement2 is the condition to execute the loop.
  3. The statement3 is executed every time after the looping code is executed.

Try this yourself:

This code is editable. Click Run to Execute


1
<html>
2
<head>
3
    <script type="text/javascript">
4
        var students = new Array("John", "Ann", "Aaron", "Edwin", "Elizabeth");
5
        document.write("<b>Using for loops </b><br />");
6
        for (i=0;i<students.length;i++)
7
        {
8
        document.write(students[i] + "<br />");
9
        }
10
    </script>
11
</head>
12
<body>
13
</body>
14
</html>
top
X
Glad to have you at Our Website
Welcome to WPBot
wpChatIcon