JavaScript function declaration, function expression, Function constructor, Anonymous function
Function declaration
function name([param[, param[, ... param]]]) {
statements
}
Example
function sum(a, b)
{
return a + b;
}
name - The function name
param - The name of the argument to be passed to the function. A function can have up to 255 arguments.
statements - The body of the function
Function expression
function [name]([param] [, param] [..., param]) {
statements
}
Example
var sum = function(a, b) { return a + b; }
Anonymous function
The name can be omitted in which case it becomes anonymous function. Anonymous functions can help make code more concise when declaring a function that will only be used in one place.
Example
var ar = [1,2,3];
var newAr = ar.map(function(e) { return e * 2});
console.log(newAr); //[2,4,6]
Function constructor
Function objects can be created with new operator
new Function (arg1, arg2, ... argN, functionBody)
Example
var sum = new Function('a','b', 'return a + b;');
arg1, arg2, … argN - zero or more names to be used by the function as argument names
functionBody - A string containing JavaScript statements forming the function body.
References
Categories :
JavaScript