Functions
A
function
is a piece of executable code that is defined by a JavaScript program
or predefined by the JavaScript implementation. Although a function
is defined only once, a JavaScript program can execute or invoke it
any number of times. A function may be passed arguments, or
parameters, specifying the value or values upon which it is to
perform its computation, and it may also return a value that
represents the results of that computation. JavaScript
implementations provide many predefined functions, such as the
Math.sin( ) function that computes the sine of an
angle.
JavaScript programs may also define their own functions with code that looks like this:
function square(x) // The function is named square. It expects one argument, x.
{ // The body of the function begins here.
return x*x; // The function squares its argument and returns that value.
} // The function ends here.Once a function is defined, you can invoke it by following the function’s name with an optional comma-separated list of arguments within parentheses. The following lines are function invocations:
y = Math.sin(x); y = square(x); d = compute_distance(x1, y1, z1, x2, y2, z2); move( );
An important feature of JavaScript is that functions are values that can be manipulated by JavaScript code. In many languages, including Java, functions are only a syntactic feature of the language -- they can be defined and invoked, but they are not data types. The fact that functions are true values in JavaScript ...