Skip to content

anonymous function

An anonymous function is a function defined without a name of its own, usually written as an expression in the spot where the code needs it.

Function expressions can leave the name out, and arrow functions never have one, so (price) => price * 2 and function () {} are both anonymous. Anonymous functions often appear as callbacks passed to array methods, timers, and event handlers, or values returned from a higher-order function. An IIFE is often anonymous too.

Being anonymous doesn’t always mean the .name property is empty. Since ES2015, a function assigned to a variable or defined as a property in an object literal takes that variable or property name. An anonymous export default function gets the name "default". A function passed straight to another function or returned from one has nothing to borrow a name from, so its .name is an empty string.

Example

Say a pricing module stores one formatter in a variable and builds another in a factory function. The .name property shows which ones picked up a name:

Language: JavaScript
> const formatPrice = (cents) => `$${(cents / 100).toFixed(2)}`;
undefined
> formatPrice.name
'formatPrice'

> function makeFormatter(currency) {
…   return (cents) => `${(cents / 100).toFixed(2)} ${currency}`;
… }
undefined
> makeFormatter("EUR").name
''

The arrow function in formatPrice is still anonymous in the source, but the const declaration gives it a name. The one returned from makeFormatter() keeps the empty name.

An anonymous function has no name to call itself by, so a recursive one has to reach itself through an outer variable. Say a checksum helper sums the digits of an order number, and later code reassigns that variable:

Language: JavaScript
> let sumDigits = function (n) {
…   return n < 10 ? n : (n % 10) + sumDigits(Math.floor(n / 10));
… };
undefined
> const checksum = sumDigits;
undefined
> sumDigits = null;
null

> try {
…   checksum(1234);
… } catch (error) {
…   error.message;
… }
'sumDigits is not a function'

The recursive call looks up sumDigits when it runs and finds null. A named function expression such as function sum(n) { ... } fixes this. Its name is a read-only variable that only the function body can see, so the recursive call always reaches the function itself.

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Nov. 22, 2026