Functions
Function declaration
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 help 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
varkeyword. - Any variable declared within a function without the
varkeyword is a global variable.
Function expression
var foo = function(){...}; // Anonymous function expression
var foo = function MyFoo(){...}; // Named function expression (easier to debug)
Immediately invoking an anonymous function
(function(){...})();
(function(x){...})(1); // With arguments
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"); Resources URL:
notes/javascript/resources
Sources URL:
notes/javascript/sources