Anonymous functions
Example of an anonymous function
javascript
const sum = function(a, b) {
return a + b;
};This function is anonymous because it has no name after the word function.
It is simply assigned to the variable sum.
What a named function looks like for comparison
javascript
function sum(a, b) {
return a + b;
}Here the function has a name - sum.
It can be used inside the function (for example, for recursion) or in the error stack.
Where anonymous functions are most often used
Anonymous functions are most often used:
- In function expressions
javascript
const multiply = function(a, b) { return a * b; };- In callbacks
javascript
setTimeout(function() {
console.log("1 second has passed");
}, 1000);- In arrow functions (also a kind of anonymous function)
javascript
const greet = () => console.log("Hello!");- In event handlers
javascript
button.addEventListener('click', function() {
console.log("Button clicked");
});Advantages
Short and concise syntax.
Great for one-off functions, especially as arguments (callback).
Used in arrow functions and modern methods (map, forEach, filter, etc.)
Disadvantages
Harder to debug - the error stack does not show the function's name:
javascript
TypeError at <anonymous>:3:10Cannot call itself recursively (without a name). Can hurt readability if used too often and nested too deeply.
Example: named vs anonymous in a callback
javascript
// Anonymous function
setTimeout(function() {
console.log("Hi");
}, 1000);
// Named function (easier to debug and reuse)
function sayHi() {
console.log("Hi");
}
setTimeout(sayHi, 1000);Quick summary
| Type | Example | Has a name? | Can be called directly? |
|---|---|---|---|
| Named | function foo() {} | Yes | Yes |
| Anonymous | function() {} | No | Only via a variable or callback |
| Arrow | () => {} | No (anonymous by nature) | Via a variable |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.