Loops
for
for (statement 1; statement 2; statement 3) { // code block to be executed }
Statement 1 is initialization, Statement 2 defines the condition for executing and Statement 3 is executed after the block has been executed.
var FaceIds = [12, 13, 14, 15];
var sum = 0, i = 0;
for(i = 0; i < 4; i++)
{
text += FaceIds[i] ;
}
while
while (condition) { // code block to be executed }
In the following example, the code in the loop will run, over and over again, as long as a variable i is less than 10.
var FaceIds = [12, 13, 14, 15];
var sum = 0, i = 0;
while (i < 4)
{
text += FaceIds[i] ;
i++;
}
do while
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
do { // code block to be executed } while (condition);
var FaceIds = [12, 13, 14, 15];
var sum = 0, i = 0;
do
{
text += FaceIds[i] ;
i++;
}while(i < 4);
break and continue
The break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in the loop.
break
The break statement breaks the loop and continues executing the code after the loop.
var sum = 0, i = 0;
for(i = 0; i < 10; i++)
{
if (i === 3)
break;
sum = sum + i;
}
when i equals 3, the loop is terminated.
continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
var sum = 0, i = 0;
for(i = 0; i < 10; i++)
{
if (i === 3)
continue;
sum = sum + i;
}
when i equals 3, the loop skips the execution of the remaining loop statements and continued with the next iteration.