execution of scripts, so instead of a for loop, just write x := x + 1; and after 10 repetitions the
appropriate code can be executed.
Three different loop types are available:
·
The while loop. It only begins if the condition is true and stops as soon as the condition
is not true anymore:
//Example: loop 10 times:
var i = 0;
while (i < 10)
{
i = i + 1; //same as i++;
}
·
The do while loop. This kind of loop will execute the code inside the loop at least once.
Only after this the break condition is evaluated:
var k = 11;
do
{
k = k + 1;
} while (k < 10);
//now k is == 12
·
The for loop. This loop is used to run the code inside for specified number of times.
The for loop statement includes 3 statements. The first is normally used to initialize a
(counter) variable. The second statement is the break condition (when the loop will end)
and the third is a statement that will be executed after each loop (normally to increment
the counter):
for (var x = 0; x < 10; x++)
{
//do something
//x will have the values 0..9
}
To exit a loop inside a loop, the command break; can be used. To skip the current loop
iteration and directly start with the next iteration, the command continue; can be used.
Two condition statements exist in JavaScript that allow code execution if one or more
conditions are true.
·
The if condition statement. If the condition inside the "if" clause is true, the line behind
(or the code block inside the brackets) gets executed. To execute special code if the
condition is not true, an "else" clause can be added behind the code of the "if" clause.
Both can be combined using else if.
var i = 42;
if (i < 42)
{
//execute this code if i is less than 42
}
else if (i === 42)
{
//execute this code if i is equal to 42
}
else