Curriculum Series

Anonymous functions — what they are and where they shine

Anonymous functions — what they are and where they shine

Anonymous functions — what they are and where they shine

JavaScript

Anonymous functions

An anonymous function is just a function literal with no name of its own. You can write one in two ways:

Classic function expression:

javascript
const myFunc = function () {
console.log('Hello');
};

Arrow form (ES6):

javascript
const myFunc = () => {
console.log('Hello');
};

Where you'll actually use them

As callbacks:

javascript
setTimeout(function () {
console.log('This runs after 2 seconds');
}, 2000);
// Or with arrow syntax
setTimeout(() => {
console.log('This runs after 2 seconds');
}, 2000);

Inside array methods:

javascript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map((num) => num * 2);

Attached to events:

javascript
button.addEventListener('click', function (e) {
console.log('Button clicked!');
});

As an IIFE (Immediately Invoked Function Expression):

javascript
(function () {
let privateVar = "I'm private";
// code here
})();

IIFEs were the pre-ES6 way of creating a private scope; today you'd usually reach for a module or block scope instead.

Finished reading?

Mark this topic as solved to track your progress.