Functions
Defining
function funct-name( ) {
statements;
return VALUE;
}
function funct-name( ARG, ARG ) {
var VAR-NAME = VALUE;
statements;
return VALUE;
}
- Define all functions in the
<head>...</head>
of an HTML page, to ensure
that the function is not called before it's been defined.
Arguments
- All arguments are passed by value.
- If an object is passed and its properties
are altered in the
function, the changes will be visible outside of the function.
- The arguments of a function are
maintained in the special array
"
arguments" (zero-based).
arguments[0] // The first argument
functionName.arguments[1] // The second argument
arguments.length // Number of arguments
Local variables
- Local variables must be declared using
the
var keyword.
- Any variable declared within a function
without the
var keyword is a global variable.
Examples
function multiply(x, y) {
var product = x * y;
return product;
}
var i = multiply(5, 7);
function subtract(x, y) {
return x - y;
}
var j = subtract(5, 3);
function myConcat() {
var result = ""; // Initialize the output.
var separator = arguments[0];
// For each argument (skipping the first one, which is the separator).
for (var i = 1; i < arguments.length; i++) {
if (i > 1) {
result += separator;
}
result += arguments[i];
}
return result;
}
// Returns "red, orange, blue"
myConcat(", ", "red", "orange", "blue");