Function Expression
The function
keyword can be used to define a function inside an expression.
const sum = function total(x, y) {
return x + y;
};
You will not be able to call the function using its name total
. Instead, you must use the alias sum
to invoke the function. In fact, in a function expression, the function name can be omitted to create anonymous functions.
const sum = function (x, y) {
return x + y;
};
In anonymous functions, you will not be able to refer to the function within itself, e.g. for recursion.
Anonymous Functions
An anonymous function is one without a name after the function
keyword:
const mean = function (x, y) {
return (x + y) / 2;
};
In contrast, a named function is one that has a name after the function
keyword.
A common use for anonymous functions is as arguments to other functions.
const numbers = [1, 2, 3, 4, 5, 6, 7]; const evens = numbers.filter(function (x) { return x % 2 === 0; }); console.log(evens);