You are on page 1of 4

While Loop:

The most basic loop in JavaScript is the while loop


The purpose of a while loop is to execute a statement or code block repeatedly as long as
expression is true. Once expression becomes false, the loop will be exited
Syntax:
While (condition)
{
code to be executed upto condition is true
}

Example: 1
Write javascript application for display 1 to 10 numbers using while-loop
<html><head><title></title>
<script language="javascript">
document.write("To display 1 to 10 numbers <br>")
var i
i=1
while (i<=10)
{
document.write(i+" ")
i++
}
</script>
</head>
<body>
</body>
</html>
Output:
To display 1 to 10 numbers
1 2 3 4 5 6 7 8 9 10

Example: 2
<html><head><title></title>
<script language="javascript">
document.write("To display even numbers between 1 to 10 <br>")
var i,j
i=1
while (i<=10)
{
if(i%2==0)
{
document.write(i+" ")

}
i++
}
j=1
document.write("<br>To display odd numbers between 1 to 10 <br>")
while (j<=10)
{
if(j%2==1)
{
document.write(j+" ")
}
j++
}
</script>
</head>
<body>
</body>
</html>

Output:

To display even numbers between 1 to 10


2 4 6 8 10
To display odd numbers between 1 to 10
13579
with Statement:
inside with statement
using with(object) we can call its functions directly

Example:

<html>
<head><title></title>
<script language="javascript">
with(document)
{
write("Good ")
write("Morning ")
write("Welcom To Home ")
write("Page")

}
</script>
</head>
<body>
</body>
</html>
Output:
Good Morning Welcom To Home Page

The For In Loop:


There is one more loop supported by JavaScript. It is called for...in loop. Executes one or more
statements for each property of an object, or each element of an array.

Syntax:
for (variablename in object or array )
{
statement or block to execute
}
In each iteration one property from object is assigned to variablename and this loop continues till
all the properties of the object.
Variable:
A variable that can be any property name of object or any element index of an array.
object, array:
An object or array over which to iterate.
Statements:
One or more statements to be executed for each property of object or each element of array

<html><head><title></title>
<script language="javascript">
var x
var a=new Array()
a[0]="One"
a[1]="Two"
a[2]="Three"
a[3]="Four"
document.write("The array elements are: <br>")
for(x in a)
{
document.write(a[x]+" ")
}
</script>
</head>
<body>
</body>
</html>

Output:

The array elements are:


One Two Three Four

You might also like