PROWAREtech
JavaScript: Tutorial - A Guide to JavaScript - Page 08
Statements
The if Statement
The if statement is given below:
var num = 6;
if (num == 5)
alert("num is equal to 5"); // single-line statement
else if (num == 7) {
alert("num is equal to 7"); // block statement
}
else {
alert("num is any value other than 5 and 7"); // block statement
}
The while Statement
The while statement is a pretest loop, which means the escape condition is evaluated before the code inside the loop
has been executed. Example while
loop:
The do-while Statement
The do-while statement is a post-test loop, which means that the escape condition is evaluated after the code inside the loop has been executed. The body of the loop is always executed at least once before the expression is evaluated.
The for Statement
The for statement is a pretest loop with the added capabilities of variable initialization before entering the loop and defining post-loop code to be executed.
The for-in Statement
The for-in statement is a strict iterative statement used to enumerate the properties of an object.
The break and continue Statements
The break and continue statements provide better control over the execution of code in a loop. The break
statement exits the loop immediately thereby forcing execution to continue with the next statement after the loop. The
continue
statement stops execution of the loop and returns execution to the test condition. It does not exit the
loop unless the loop test condition is false.
var num = 0;
for (var i = 1; i < 10; i++) {
if (i % 5 == 0) {
break;
}
num++;
}
alert(num); // num is 4
var num = 0;
for (var i = 1; i < 10; i++) {
if (i % 5 == 0) {
continue; // this skips the "num++;" statement
}
num++;
}
alert(num); // num is 8
The switch Statement
A switch statement can clean up a complex if-else statement.
var num = 10;
switch (num) {
case 20:
case 30:
alert("num is 20 or 30");
break;
case 40:
alert("num is 40");
break;
default:
alert("num is a value other than 20, 30 or 40");
}