Loop in Javascript
What is Loop?

Loop execute some statement many times depend upon the condition.

loop has three type. these loops do same work execute statement many times until condition is fullfil.
1.While loop
2.Do while loop
3.For loop

While Loop

In the while loop it first check the condition then body of the loop will be executed many times till the condition is fullfill.
Syntax:
while (condition)
 {
  body of code;
 }

Example 1:- To use of while loop

<html>
<head>
<title>My Javascript Code</title>
</head>
<body>
<script type="text/javascript" language="javascript">
var i=1;
while(i<=5)
{
document.write("welcome<br>");
i++;
}
</script>
</body>
</html>

Output:-
Welcome
Welcome
Welcome
Welcome
Welcome

do while loop

In the do while loop, it first execute body of the loop then check the condition if condition is not true then next time loop will not be executed otherwise loop will be executed.

Note: In the do while loop at least one time loop will be execute. because it first execute the body of the loop but in while it first check the condition then execute the body of the loop.

Syntax:-
do
 {
  body of code;
 }while (condition);

Example 2:- To use of do while loop

<html>
<head>
<title>My Javascript Code</title>
</head>
<body>
<script type="text/javascript" language="javascript">
var i=1;
do
{
document.write(i);
i++;
}while(i<=5);
</script>
</body>
</html>

Output:
1 2 3 4 5

for loop

In For loop then statement will be excuted till the condition is fullfill.
for (initilization; condition; increment)
{
  body code;
}

Example 3:- To use of for loop

My Javascript Code

<html>
<head>
<title>My Javascript Code</title>
</head>
<body>
<script type="text/javascript" language="javascript">
for(i=1;i<=5;i++)
{
document.write(i+"<br>");
}
</script>
</body>
</html>

Output:-
1
2
3
4
5


Previous
Next