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
1const myFunc = function () {
2 console.log('Hello');
3};

Arrow form (ES6):

JAVASCRIPT
1const myFunc = () => {
2 console.log('Hello');
3};

Where you'll actually use them

As callbacks:

JAVASCRIPT
1setTimeout(function () {
2 console.log('This runs after 2 seconds');
3}, 2000);
4
5// Or with arrow syntax
6setTimeout(() => {
7 console.log('This runs after 2 seconds');
8}, 2000);

Inside array methods:

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

Attached to events:

JAVASCRIPT
1button.addEventListener('click', function (e) {
2 console.log('Button clicked!');
3});

As an IIFE (Immediately Invoked Function Expression):

JAVASCRIPT
1(function () {
2 let privateVar = "I'm private";
3 // code here
4})();

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.