AJAX - The Complete Reference

(avery) #1

576 Part IV: Appendixes


Conditional Statements


JavaScript supports the common if conditional, which has numerous forms.

if (expression) statement(s)
if (expression) statement(s) else statement(s)
if (expression) statement(s) else if (expression) statement(s) ...
if (expression) statement(s) else if (expression) statement(s) else
statement(s)

An example if statement is demonstrated here.

if (hand < 17)
alert("Better keep hitting");
else if ((hand >= 17) && (hand <= 21))
alert("Stand firm");
else
alert("Busted!");

Given the verbosity of a nested if statement, JavaScript, like many languages, supports
the switch statement, whose syntax is:

switch (expression)
{
case val1: statement
[ break; ]
case val2: statement
[ break; ]
...
default: statement
}

A simple switch statement is shown here:

var ticket="First Class";
switch (ticket)
{
case "First Class": alert("Big Bucks");
break;
case "Business": alert("Expensive, but worth it?");
break;
case "Coach": alert("A little cramped but you made it.");
break;
default: alert("Guess you can’t afford to fly?");
}

The break statement is used to exit the block associated with a switch, and it must be
included to avoid fall-through for the various cases that may be unintended. Omission of
break may be purposeful, however, as it allows for the easy simulation of an “or” condition.
Free download pdf