JavaScript Tutorial - "switch/case" blocks

Left
Right

The if/else block is a versatile way to conditionally execute different blocks of code depending on the conditions.

Another way to conditionally execute blocks of code is the "switch/case" block.

The only condition is the matching of the switch expression with one of the case constant values.

All statements are executed after the case statement until a break if found. This behavior gives a primitive way to execute common code for differing cases.

The form of the switch/case block is given as follow:
Note that the breaks and default: statements, as well as the code blocks are optional.

switch ( expression ) {
case 
	block of code if true ...
}
------ In the examples, we will show a more complicated case where successive tests are performed until one of them returns a true. If none are true then the final else block is executed.

The final else block is optional.

The basic form of a if/else block is one of the following:
Simple if -

if ( conditional ) {
	block of code if true ...
}

Simple if/else -

if ( conditional ) {
	block of code if true ...
} else {
	block of code if false ...
}

Compound if/else if/else (which can be extended with more else ifs -

if ( conditional1 ) {
	block of code if conditional1 is true ...
} else if ( conditional2 ) {
	block of code if conditional2 is true ...
} else {
	block of code if all conditionals are false ...
}

The most common true conditions should be placed at the beginning of a compound if/else if block so unnecessary conditional evaluations need to be performed.

Example: work/ifelse.html

<HTML>
<BODY>
<CENTER>
<TABLE BORDER=1>
<SCRIPT LANGUAGE="JavaScript">
for (i = 1; i < 17; i++) {
	document.write('<TR><TH>',i,'</TH><TH>');
	if (i%4 == 0) {
		document.write('Divisible by 4');
	} else if (i%3 == 0) {
		document.write('Divisible by 3');
	} else if (i%2 == 0) {
		document.write('Even');
	} else {
		document.write('Odd');
	}
	document.write('</TH></TR>');
}
</SCRIPT>
</TABLE>
</CENTER>
</BODY>
</HTML>

HOMEWORK:

Left
Right
Slide 13