The JavaScript loops are used to iterate the piece of code.We have for, while, do while loops. It makes the code compact.
Looping is what makes computer programming worthwhile.
There are three types of loops in JavaScript.
1)for loop
2)while loop
3)do-while loop.
1) 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.
example of for loop
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
2) JavaScript 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.
example of while loop
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
3) 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.
example of do while loop
<script>
var i=21;
do{
document.write(i + "
");
i++;
}while (i<=25);
</script>
0 Comment(s)