Anonymous functions
suggest changeAn anonymous function has no explicit name in its syntax. It must appear where an expression is allowed—for example, as a callback, an assigned value, or an immediately invoked function expression (IIFE). A bare anonymous function declaration is a syntax error.
Assigning a function
const greet = function (name) {
return `Hello, ${name}`;
};
greet("Ada");
Although the function expression is anonymous in source, runtimes often infer a diagnostic name such as "greet" from its assignment context.
Passing a callback
Functions are values and can be passed to other functions. Here, map() calls the arrow function once for each element and returns a new array:
const numbers = [0, 1, 2];
const doubled = numbers.map((number) => number * 2);
// [0, 2, 4]
A named callback can make stack traces and recursion clearer when the operation is not trivial.
Returning a function
function multiplyBy(factor) {
return (value) => value * factor;
}
const double = multiplyBy(2);
console.log(double(4)); // 8
The returned function closes over factor, so the value remains available after multiplyBy() returns.
Immediately invoking a function
An IIFE creates a function scope and runs immediately:
(() => {
const message = "not global";
console.log(message);
})();
IIFEs remain useful in classic scripts, but ECMAScript modules already have their own top-level scope. Blocks also provide scope for let, const, and class declarations.
Recursion and function names
A named function expression can refer to itself without depending on the variable that contains it:
const factorial = function calculate(n) {
if (!Number.isInteger(n) || n < 0) {
throw new RangeError("n must be a non-negative integer");
}
return n === 0 ? 1 : n * calculate(n - 1);
};
The name calculate is visible only inside the function body. Outside it, callers use the factorial binding.