LOOP

Loop is used to reuse any code again and again there are three types of loop in javascript
1) For loop
2) While loop
3) Do while loop.

JavaScript For loop

The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of iteration is known. The syntax of for loop is given below.
Syntax:
for (initialization; condition; increment)
{
code to be executed
}

Example

W.A.P to Print 10 times hello
<html>
<head>
<title>loop</title>
<script>
var i;
for(i=1;i<=10;i++)
{
document.write("<br>hello");
}
</script>
</head>
<body>
</body>
</html>

W.A.P to Print 1 to 10
<html>
<head>
<title>loop</title>
<script>
var i;
for(i=1;i<=10;i++)
{
document.write("<br>i=",i);
}
</script>
</head>
<body>
</body>
</html>

W.A.P to Print Table
<html>
<head>
<title>loop</title>
</head>
<body>
<script>
var i,j,k;
j=parseInt(prompt("Enter a no:"));
for(i=1;i<=10;i++)
{
k=j*i;
document.write("<br>k=",k);
}
</script>
</body>
</html>

While Loop

The JavaScript while loop iterates the elements for the infinite number of times. It should be used if number of iteration is not known.

intilization(i=1)
while (condition)
{
code to be executed
Iteration(i++)
}
W.A.P to Print 1 to 10
<html>
<head>
<title>loop</title>
<script>
var i;
i=1;
while(i<=10)
{
document.write("<br>i=",i);
i++;
}
</script>
</head>
<body>
</body>
</html>

JavaScript do while loop

The JavaScript do while loop iterates the elements for the infinite number of times like while loop. But, code is executed at least once whether condition is true or false. The syntax of do while loop is given below.
do
{
intilization(i=1)
code to be executed
Iteration(i++)
}while (condition);


W.A.P to Print 1 to 10

<html>
<head>
<title>loop</title>
<script>
var i;
i=1;
do
{
document.write("<br>i=",i);
i++;
}while (i<=10);
</script>
</head>
<body>
</body>
</html>