JS function
The function declaration defines a function with the specified parameters.
Syntax
function name([param,[, param,[..., param]]]) {
[statements]
}
name
- The function name.
param
- The name of an argument to be passed to the function. A function can have up to 255 arguments.
statements
- The statements which comprise the body of the function.
Description
A 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.
Conditionally created functions
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 declaration hoisting
Function declarations in JavaScript are hoisting the function definition. You can use the function before you declared it:
hoisted();
function hoisted() {
console.log("foo");
}
Note that function expressions
are not hoisted:
notHoisted();
var notHoisted = function() {
console.log("bar");
};
Examples
function product(a,b)
{
return a*b;
}