Function Expressions

A function expression is a function defined inside an expression, usually by assigning it to a variable. We can do this because a function is a value like any other value.

const sum = function total(x, y) {
  return x + y;
};

console.log(sum(2, 3)); // 5

In the example above, the function is named total, but when we assign it to the variable sum, we must use sum to call the function. The original name total is not accessible outside of the function’s own body.

Most of the time we write a function expression without naming the function. A function with no name is called an anonymous function. Anonymous functions are useful when a function is used only once, or only in a small part of the code.

const sum = function (x, y) {
  return x + y;
};

console.log(sum(2, 3)); // 5

An anonymous function expression does not create an internal name binding inside the function body, so the function cannot call itself by an internal name.

const fact = function (n) {
  return n <= 1 ? 1 : n * fact(n - 1); // recursion via variable reference
};

For recursion, we have two options. We can call the function through a reference we have kept, such as the variable we assigned it to. Or we can use a named function expression, which gives the function an internal name.

const fact2 = function f(n) {
  return n <= 1 ? 1 : n * f(n - 1); // recursion via internal name
};

Anonymous Functions in Higher-Order Functions

We often pass an anonymous function as an argument to another function or method, especially to one that expects a callback function. Array methods are the most common example.

const numbers = [1, 2, 3, 4, 5, 6, 7];
const evens = numbers.filter(function (x) {
  return x % 2 === 0;
});

console.log(evens); // [2, 4, 6]

The `.filter` method receives a callback function as an argument. This function is called for each element in the array, and if it returns true, the element is included in the result.

This pattern is common in JavaScript. It lets us write a small piece of behavior where we need it, without adding a function name to the scope that we do not need anywhere else.