How to Loop using JavaScript?

Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true. In JavaScript there are two different kinds of loops which are for loop, which loops through a block of code a specified number of times and while loop, which loops through a block of code while a specified condition is true.

JavaScript For Loop

The for loop is used when you know in advance how many times the script should run.

Syntax:

for(var=startvalue; var<=endvalue;var=var+increment)
{
code to be executed
}

Example:

<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var i=0
for (i=0;i<=10;i++){
document.write(“The number is” +i)
document.write(“<br/>”)}
</script>
</body>
</html>

The above example defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

Preview: