Skip to main content

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:

  1. In function expressions
javascript
const multiply = function(a, b) { return a * b; };
  1. In callbacks
javascript
setTimeout(function() { console.log("1 second has passed"); }, 1000);
  1. In arrow functions (also a kind of anonymous function)
javascript
const greet = () => console.log("Hello!");
  1. 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:10

Cannot 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

TypeExampleHas a name?Can be called directly?
Namedfunction foo() {}YesYes
Anonymousfunction() {}NoOnly via a variable or callback
Arrow() => {}No (anonymous by nature)Via a variable

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.