↑
Main Page
No overloading
return iNum1 – iNum2;
} else {
return iNum2 – iNum1;
}
}
The previous function is designed to return the difference between two numbers. To do so, it must
always subtract the smaller number from the larger, which results in an
if
statement to determine
which
return
statement to execute.
If a function doesn’t return a value, it can use the return operator without any parameters to exit a func-
tion at any time. Example:
function sayHi(sMessage) {
if (sMessage == “bye”){
return;
}
alert(sMessage);
}
In this code, the alert will never be displayed if the message is equal to the string
“bye”
.
No overloading
ECMAScript functions cannot be overloaded. This may come as a surprise, considering ECMAScript
closely resembles other higher-level programming languages that support overloading. You can define
two functions with the same name in the same scope without an error; however, the last function
becomes the one that is used. Consider the following example:
function doAdd(iNum) {
alert(iNum + 100);
}
function doAdd(iNum) {
alert(iNum + 10);
}
doAdd(10);
What do you think will be displayed from this code snippet? The alert will show
“20”
, because the sec-
ond
doAdd()
definition overwrites the first. Although this can be annoying to a developer, you have a
way to work around this limitation by using the
arguments
object.
When a function doesn’t explicitly return a value or uses the return statement with-
out a value, the function actually returns
undefined
as its value.
61
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 61
Free JavaScript Editor
Ajax Editor
©
→