JavaScript

What is an anonymous function and when would you use it?

Anonymous functions

An anonymous function in JavaScript is a function that is defined without a name. It can we created in the following ways:

Using traditional function syntax:

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

Using arrow function syntax (introduced in ES6):

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

Anonymous functions are commonly used in several scenarios

As callback functions:

setTimeout(function () {
console.log('This runs after 2 seconds');
}, 2000);

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

In array methods:

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

As event handlers:

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

In Immediately Invoked Function Expressions (IIFE):

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