You are on page 1of 2

For loop:

The for loop is use when you want to create a loop

Syntax:
for (initialization; condition; iteration statement)
{
code to be executed if condition is true
}

The for loop is the most compact form of looping and includes the following three important parts:

1) initialization :
The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.

2) condition:

The test statement which will test if the given condition is true or not. If condition is true
then code given inside the loop will be executed otherwise loop will come out.

3) iteration statement :
The iteration statement where you can increase or decrease your counter

You can put all the three parts in a single line separated by a semicolon

Example 1:

Write javascript application for display 1 to 10 numbers using for loop

<html>
<head>
<title>Title of the document</title>
<script language="javascript">
var num,i
document.write("The 1 to 10 numbers are: <br>")
for (i=1;i<=10;i++)
{
document.write(i+" ")
}
</script>
</head>
<body>
</body>
</html>
Output:

The 1 to 10 numbers are:


1 2 3 4 5 6 7 8 9 10

Example 2:

Write javascript application for display even and odd numbers from 1 to 10 using for loop

<html><head><title></title>
<script language="javascript">
var num,i
document.write("The even numbers between 1 to 10 are: <br>")
for (i=1;i<=10;i++)
{
if (i%2==0)
{
document.write(i+" ")
}
}
document.write("<br>The odd numbers between 1 to 10 are: <br>")
for (i=1;i<=10;i++)
{
if (i%2==1)
{
document.write(i+" ")
}
}
</script>
</body>
</html>

Output:

The even numbers between 1 to 10 are:


2 4 6 8 10
The odd numbers between 1 to 10 are:
13579

You might also like