Main Page

Functions

Essentially, the
switch
statement prevents a developer from having to write something like this:
if (i == 25)
alert(“25”);
else if (i == 35)
alert(“35”);
else if (i == 45)
alert(“45”);
else
alert(“Other”);
The equivalent
switch
statement is:
switch (i) {
case 25: alert(“25”);
break;
case 35: alert(“35”);
break;
case 45: alert(“45”);
break;
default: alert(“Other”);
}
Two big differences exist between the
switch
statement in ECMAScript and Java. In ECMAScript, the
switch
statement can be used on strings, and it can indicate case by nonconstant values:
var BLUE = “blue”, RED = “red”, GREEN = “green”;
switch (sColor) {
case BLUE: alert(“Blue”);
break;
case RED: alert(“Red”);
break;
case GREEN: alert(“Green”);
break;
default: alert(“Other”);
}
Here, the
switch
statement is used on the string
sColor
, whereas the
case
s are indicated by using the
variables
BLUE
,
RED
, and
GREEN
, which is completely valid in ECMAScript.
Functions
Functions are the heart of ECMAScript: a collection of statements that can be run anywhere at anytime.
Functions are declared with the keyword function, followed by a set of arguments, and finally by the
code to execute enclosed in braces. The basic syntax is:
function
functionName
(
arg0, arg1,...,argN
) {
statements
}
59
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 59


JavaScript EditorFree JavaScript Editor     Ajax Editor


©

R7