fcns
Previous Contents Index Next |
Core JavaScript Guide 1.5 |
Chapter 6 Functions
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a specific task. To use a function, you must first define it; then your script can call it.
This chapter contains the following sections:
Defining Functions
A function definition consists of the function keyword, followed by
The name of the function. A list of arguments to the function, enclosed in parentheses and separated by commas. The JavaScript statements that define the function, enclosed in curly braces, { }. The statements in a function can include calls to other functions defined in the current application. For example, the following code defines a simple function named square:
function square(number) {
return number * number;
}
The function square takes one argument, called number. The function consists of one statement that indicates to return the argument of the function multiplied by itself. The return statement specifies the value returned by the function.
All parameters are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function. However, if you pass an object as a parameter to a function and the function changes the object's properties, that change is visible outside the function, as shown in the following example:
function myFunc(theObject) {
theObject.make="Toyota"
}
mycar = {make:"Honda", model:"Accord", year:1998};
x=mycar.make; // returns Honda
myFunc(mycar); // pass object mycar to the function
y=mycar.make; // returns Toyota (prop was changed by the function)
A function can be defined based on a condition. For example, given the following function definition:
if (num == 0)
{
function myFunc(theObject) {
theObject.make="Toyota"
}
}
the myFunc function is only defined if the variable num equals 0. If num does not equal 0, the function is not defined, and any attempt to execute it will fail.
In addition to defining functions as described here, you can also define Function objects, as described in "Function Object" on page 106.
A method is a function associated with an object. You'll learn more about objects and methods in Chapter 7, "Working with Objects."
A function can also be defined inside an expression. This is called a function expression. Typically such a function is anonymous; it does not have to have a name. For example, the function square could have been defined as:
const square = function(number) {return number * number};
This is convenient when passing a function as an argument to another function. The following example shows the map function being defined and then called with an anonymous function as its first parameter:
function map(f,a) {
var result=new Array;
for (var i = 0; i != a.length; i++)
result[i] = f(a[i]);
return result;
}
map(function(x) {return x * x * x}, [0, 1, 2, 5, 10];
Defining a function does not execute it. Defining the function simply names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function square, you could call it as follows.
The preceding statement calls the function with an argument of five. The function executes its statements and returns the value twenty-five.
The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function, too. The show_props function (defined in "Objects and Properties" on page 91) is an example of a function that takes an object as an argument.
A function can even be recursive, that is, it can call itself. For example, here is a function that computes factorials:
function factorial(n) {
if ((n == 0) || (n == 1))
return 1
else {
var result = (n * factorial(n-1) );
return result
}
}
You could then compute the factorials of one through five as follows:
a=factorial(1) // returns 1
b=factorial(2) // returns 2
c=factorial(3) // returns 6
d=factorial(4) // returns 24
e=factorial(5) // returns 120
The arguments of a function are maintained in an array. Within a function, you can address the arguments passed to it as follows:
where i is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be arguments[0]. The total number of arguments is indicated by arguments.length.
Using the arguments array, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then treat each argument using the arguments array.
For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:
function myConcat(separator) {
var result="" // initialize list
// iterate through arguments
for (var i=1; i<arguments.length; i++) {
result += arguments[i] + separator
}
return result
}
You can pass any number of arguments to this function, and it creates a list using each argument as an item in the list.
// returns "red, orange, blue, "
myConcat(", ","red","orange","blue")
// returns "elephant; giraffe; lion; cheetah; "
myConcat("; ","elephant","giraffe","lion", "cheetah")
// returns "sage. basil. oregano. pepper. parsley. "
myConcat(". ","sage","basil","oregano", "pepper", "parsley")
See the Function object in the Core JavaScript Reference for more information.
JavaScript 1.3 and earlier versions. The arguments array is a property of the Function object and can be preceded by the function name, as follows:
JavaScript has several top-level predefined functions:
eval isFinite isNaN parseInt and parseFloat Number and String encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent (all available with Javascript 1.5 and later). The following sections introduce these functions. See the Core JavaScript Reference for detailed information on all of these functions.
eval Function
The eval function evaluates a string of JavaScript code without reference to a particular object. The syntax of eval is:
where expr is a string to be evaluated.
If the string represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements. Do not call eval to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.
isFinite Function
The isFinite function evaluates an argument to determine whether it is a finite number. The syntax of isFinite is:
where number is the number to evaluate.
If the argument is NaN, positive infinity or negative infinity, this method returns false, otherwise it returns true.
The following code checks client input to determine whether it is a finite number.
if(isFinite(ClientInput) == true)
{
/* take specific steps */
}
isNaN Function
The isNaN function evaluates an argument to determine if it is "NaN" (not a number). The syntax of isNaN is:
where testValue is the value you want to evaluate.
The parseFloat and parseInt functions return "NaN" when they evaluate a value that is not a number. isNaN returns true if passed "NaN," and false otherwise.
The following code evaluates floatValue to determine if it is a number and then calls a procedure accordingly:
floatValue=parseFloat(toFloat)
if (isNaN(floatValue)) {
notFloat()
} else {
isFloat()
}
parseInt and parseFloat Functions
The two "parse" functions, parseInt and parseFloat, return a numeric value when given a string as an argument.
where parseFloat parses its argument, the string str, and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), a numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, it returns "NaN" (not a number).
parseInt parses its first argument, the string str, and attempts to return an integer of the specified radix (base), indicated by the second, optional argument, radix. For example, a radix of ten indicates to convert to a decimal number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than nine. For example, for hexadecimal numbers (base 16), A through F are used.
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. If the first character cannot be converted to a number in the specified radix, it returns "NaN." The parseInt function truncates the string to integer values.
Number and String Functions
The Number and String functions let you convert an object to a number or a string. The syntax of these functions is:
where objRef is an object reference.
The following example converts the Date object to a readable string.
D = new Date (430054663215)
// The following returns
// "Thu Aug 18 04:37:43 GMT-0700 (Pacific Daylight Time) 1983"
x = String(D)
escape and unescape Functions
The escape and unescape functions let you encode and decode strings. The escape function returns the hexadecimal encoding of an argument in the ISO Latin character set. The unescape function returns the ASCII string for the specified hexadecimal encoding value.
The syntax of these functions is:
escape(string)
unescape(string)
These functions are used primarily with server-side JavaScript to encode and decode name/value pairs in URLs.
The escape and unescape functions do not work properly for non-ASCII characters and have been deprecated. In JavaScript 1.5 and later, use encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent.
Previous Contents Index Next
Content is available under these licenses.
Last Updated September 28, 2000
Leave a Response
(0 comments)