PROWAREtech

articles » current » javascript » tutorial » page-08

JavaScript: Tutorial - A Guide to JavaScript - Page 08

Language Basics (Statements: while, do-while, for, for-in, break, continue, switch).

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:

var num = 0;
while(num++ < 5){
	alert(num);
}

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.

var num = 0;
do {
	alert(num);
} while (num++ < 3);

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.

for(var i = 0; i < 3; i++) {
	alert(i);
}

The for-in Statement

The for-in statement is a strict iterative statement used to enumerate the properties of an object.

for (var prop in window) {
	alert(prop);
}

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");
}
<<<[Page 8 of 22]>>>

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE