|
Looping
Very often when you write code, you want allow the same block of
code to run a number of times. You can use looping statements in
your code to do this.
In JavaScript we have the following looping statements:
· while - loops through a block of code while a condition
is true
· do...while - loops through a block of code once, and
then it repeats the loop while a condition is true
· for - run statements a specified number of times
while
The while statement will execute a block of code while a
condition is true..
while (condition)
{
code to be executed
}
do...while
The do...while statement will execute a block of code once, and
then it will repeat the loop while a condition is true
do
{
code to be executed
} while (condition)
for
The for statement will execute a block of code a specified
number of times
for (initialization; condition; increment)
{
code to be executed
}
Examples
1.How to write a For loop. Use a For loop to run the same block
of code a specified number of times
Coding
<html>
<body>
<script language="JavaScript">
for (i = 0; i <= 5; i++)
{
document.write("The number is " + i)
document.write("<br>")
}
</script>
</body>
</html>
Output
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
2.How to use the For loop to write the HTML headers.
Coding
<html>
<body>
<script language="JavaScript">
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">This is header " + i)
document.write("</h" + i + ">")
}
</script>
</body>
</html>
Output
This is header 1
This is header 2
This is header 3
This is header 4
This is header 5
This is header 6
3.How to write a While loop. Use a While loop to run the same
block of code while or until a condition is true
Coding
<html>
<body>
<script language="JavaScript">
i = 0
while (i <= 5)
{
document.write("The number is " + i)
document.write("<br>")
i++
}
</script>
</body>
</html>
Output
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
4.How to write a Do While loop. Use a Do While loop to run the
same block of code while or until a condition is true. This loop
will always be executed once, even if the condition is false,
because the statements are executed before the condition is
tested
Coding
<html>
<body>
<script language="JavaScript">
i = 0
do
{
document.write("The number is " + i)
document.write("<br>")
i++
}
while (i <= 5)
</script>
</body>
</html>
Output
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5 |