The function declaration defines a function with the specified parameters.
You can also define functions using the Function constructor and a function expression.
function name([param,[, param,[..., param]]]) {
[statements]
}
nameparamstatementsA function created with a function declaration is a Function object and has all the properties, methods and behavior of Function objects. See Function for detailed information on functions.
A function can also be created using an expression (see function expression).
By default, functions return undefined. To return any other value, the function must have a return statement that specifies the value to return.
Functions can be conditionally declared, that is, a function statement can be nested within an if statement. Most browsers other than Mozilla will treat such conditional declarations as an unconditional declaration and create the function whether the condition is true or not, see this article for an overview. Therefore they should not be used, for conditional creation use function expressions.
Function declarations in JavaScript are hoisting the function definition. You can use the function before you declared it:
hoisted(); // logs "foo"
function hoisted() {
console.log("foo");
}
Note that function expressions are not hoisted:
notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function() {
console.log("bar");
};
functionThe following code declares a function that returns the total amount of sales, when given the number of units sold of products a, b, and c.
function calc_sales(units_a, units_b, units_c) {
return units_a*79 + units_b * 129 + units_c * 699;
}
Created by Mozilla Contributors, license: CC-BY-SA 2.5