JavaScript Tutorial - "if/else" blocks

Left
Right

We have seen conditionals that return a boolean value of true or false.

Conditionals have been used to express when a loop should end, such as in a for loop.

However, we may want to conditionally execute some blocks of code for one condition, and a different block of code under some other condition.

This is accomplished with the "if/else" block.

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 12