Professional Documents
Culture Documents
While Loop
While Loop
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:
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
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: