JavaScriptMedium
When are anonymous functions useful?
By FrontendPro Editorial Team Updated 9/26/2026
#JavaScript
Answer
An anonymous function is one with no name of its own. You use it wherever the function is passed straight to something else and never needs to be referenced again — callbacks, handlers, and one-shot initialisers.
The three common shapes
js
// 1. argument to a higher-order function
items.filter(item => item.active);
button.addEventListener('click', () => setOpen(true));
// 2. immediately invoked, to scope some setup work
(async () => {
const config = await load();
start(config);
})();
// 3. closure returned from a factory
const makeAdder = n => x => x + n;
Why not always name them
A name costs a line and a decision, and for a two-token callback it buys nothing. But naming pays off in three places:
- Stack traces. A named function expression shows its name in the trace; an anonymous arrow shows the inferred variable name at best, and
<anonymous>when there is nothing to infer. - Recursion. The function needs a name to call itself.
- Removing a listener.
removeEventListenercompares by reference, so an inline arrow can never be removed.
js
const onClick = () => setOpen(true); // keep a reference
el.addEventListener('click', onClick);
el.removeEventListener('click', onClick);
One more difference
Arrow functions have no this of their own, no arguments, and cannot be used with new. That is usually the reason to pick one — it inherits this from where it was written, which is what you want inside a class method or a React component.
