JavaScript Loops
for
while
do while
The for loop has the following syntax:
{
code block to be executed
}
code block to be executed
}
Example
for (i = 0; i < 5; i++)
{
text += "The number is " + i + "<br>";
}
text += "The number is " + i + "<br>";
}
The While Loop Syntax
while (condition)
{
code block to be executed
}
Example
In the following example, the code in the loop will run, over and over again, as long as
a variable (i) is less than 5:
Example
while (i < 5)
{
text += "The number is " + i;
i++;
}
text += "The number is " + i;
i++;
}
The Do/While Loop Syntax
The do/while loop is a variant of the while loop.
do {
code block to be executed
}
while (condition);
Example
The example below uses a do/while loop. The loop will always be
executed at least once, even if the condition is false, because the code block
is executed before the condition is tested:
Example
do {
text += "The number is " + i;
i++;
}
while (i < 10);
No comments:
Post a Comment