In this tutorial, we will learn-
How to use Loop?
Different Types of Loops
for loop
while loop
do…while 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.
There are mainly four types of loops in JavaScript.
for loop
for/in a loop (explained later)
while loop
do…while loop
Syntax:
for(statement1; statement2; statment3)
{
lines of code to be executed
}
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.
The statement2 is the condition to execute the loop.
The statement3 is executed every time after the looping code is executed.
Input
Output
<html>
<head>
<script type="text/javascript">
var students = new Array("John", "Ann", "Aaron", "Edwin", "Elizabeth");
document.write("<b>Using for loops </b><br />");
for (i=0;i<students.length;i++)
{
document.write(students[i] + "<br />");
}
</script>
</head>
<body>
</body>
</html>
while(condition)
{
lines of code to be executed
}
The “while loop” is executed as long as the specified condition is true. Inside the while loop, you should include the statement that will end the loop at some point of time. Otherwise, your loop will never end and your browser may crash.
Input
Output
<html>
<head>
<script type="text/javascript">
document.write("<b>Using while loops </b><br />");
var i = 0, j = 1, k;
document.write("Fibonacci series less than 40<br />");
while(i<40)
{
document.write(i + "<br />");
k = i+j;
i = j;
j = k;
}
</script>
</head>
<body>
</body>
</html>