- Classic definition (anonymous function)
function (arg1, arg2, ...) {
statements
}
- New definition (anonymous function)
(arg1, arg2, ...) => expression
(arg1, arg2, ...) => {
statements
}
In the first case, the expresison is automatically returned. In the second,
you need a return statement to return a value.
- JavaScript uses anonymous functions often, but naming them is simple.
let f1 = name(arg1, arg2, ...) {
statements
}
let f2 = (arg1, arg2, ...) => {
statements
}
- And the classic form, which looks more like other scripting languages:
function f3 (arg1, arg2, ...) {
statements
}
- Arguments passed in the same way Java does, by value for simple
things and by reference value for objects.
- Functions may be called with fewer arguments than parameters, and
the extra parameters have the value undefined.
- Default values are allowed.
- Default is used instead of undefined
if the parameter is not sent.
function(a = 4, b, c = 'foobar').
- Note that any parameter may (or not) have a default; no rule about
only on the right as in C++.
- Variadic parameter lists are supported:
function(a,b, ...rest) { }
Assigns the third and following parameter to the array-like
variable rest (any variable name).
- Functions have a special array-like variable arguments
- Can be used as an array, with subscripts from zero.
- Contains all arguments sent, regardless parameter names.
function addem() {
let s = 0;
for (var p of arguments) { s += p };
return s;
}
- Functions created with function are hoisted like vars.
Functions created with => are not, and also do not have an
arguments variable. The arrow syntax is newer, and,
apparently, cooler.