An anonymous function is a function without a name.

function () {
console.log("Hello");
}

⚠️ This alone is invalid because anonymous functions must be used as a value.

Anonymous Function

  • A function without a name
  • Usually stored in a variable, passed as an argument, or used immediately
  • Common in callbacks, event handlers, and functional programming

1.Syntax of Anonymous Function

Function Expression

const greet = function () {
console.log("Hello!");
};
greet(); // Hello!

✔ Function has no name
✔ Variable name is used to call it

2.Anonymous Function as Callback

Example: setTimeout

setTimeout(function () {
console.log("Executed after 1 second");
}, 1000);

✔ Function passed as argument
✔ No name needed because it’s used only once

3.Anonymous Functions in Event Handlers

button.addEventListener("click", function () {
alert("Button clicked");
});

✔ Clean and readable
✔ Common real-world use case

4.Anonymous Functions with Array Methods

const numbers = [1, 2, 3, 4];

const squares = numbers.map(function (n) {
return n * n;
});

console.log(squares); // [1, 4, 9, 16]

✔ Functions passed directly
✔ No unnecessary naming

5.Arrow Functions (Anonymous by Default)

Arrow functions are modern anonymous functions.

const add = (a, b) => a + b;

Used as callback:

numbers.filter(n => n % 2 === 0);

✔ Short syntax
✔ Preferred for callbacks

6.Immediately Invoked Anonymous Function (IIFE)

(function () {
console.log("Runs immediately");
})();

✔ Executes immediately
✔ Creates private scope

Arrow version:

(() => {
console.log("IIFE with arrow");
})();

7.Anonymous Function as Return Value

function multiplier(x) {
return function (y) {
return x * y;
};
}
const double = multiplier(2);
console.log(double(5)); // 10

✔ Creates closures
✔ Functions returned as values

8.Anonymous Functions in Promises

fetch(url)
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
});

Arrow version:

fetch(url)
.then(res => res.json())
.then(data => console.log(data));

Categorized in:

Javascript,