Skip to main content

What's a typical use case for anonymous functions in JavaScript?

TL;DR​

An anonymous function in JavaScript is a function that does not have any name associated with it. They are typically used as arguments to other functions or assigned to variables.

const arr = [-1, 0, 5, 6];

// The filter method is passed an anonymous function.
arr.filter((x) => x > 1); // [5, 6]

They are often used as arguments to other functions, known as higher-order functions, which can take functions as input and return a function as output. Anonymous functions can access variables from the outer scope, a concept known as closures, allowing them to "close over" and remember the environment in which they were created.

// Encapsulating Code
(function () {
// Some code here.
})();

// Callbacks
setTimeout(function () {
console.log('Hello world!');
}, 1000);

// Functional programming constructs
const arr = [1, 2, 3];
const double = arr.map(function (el) {
return el * 2;
});
console.log(double); // [2, 4, 6]

Anonymous functions​

Anonymous functions provide a more concise way to define functions, especially for simple operations or callbacks. Besides that, they can also be used in the following scenarios.

Immediate execution​

Anonymous functions are commonly used in Immediately Invoked Function Expressions (IIFEs) to encapsulate code within a local scope. This prevents variables declared within the function from leaking to the global scope and polluting the global namespace.

// This is an IIFE
(function () {
var x = 10;
console.log(x); // 10
})();

// x is not accessible here
console.log(typeof x); // undefined

In the above example, the IIFE creates a local scope for the variable x. As a result, x is not accessible outside the IIFE, thus preventing it from leaking into the global scope.

Callbacks​

Anonymous functions can be used as callbacks that are used once and do not need to be used anywhere else. The code will seem more self-contained and readable when handlers are defined right inside the code calling them, rather than having to search elsewhere to find the function body.

setTimeout(() => {
console.log('Hello world!');
}, 1000);

Higher-order functions​

They are used as arguments to functional programming constructs like higher-order functions or Lodash (similar to callbacks). Higher-order functions take other functions as arguments or return them as results. Anonymous functions are often used with higher-order functions like map(), filter(), and reduce().

const arr = [1, 2, 3];
const double = arr.map((el) => {
return el * 2;
});
console.log(double); // [2, 4, 6]

Event Handling​

In React, anonymous functions are widely used for defining callback functions inline for handling events and passing callbacks as props.

function App() {
return <button onClick={() => console.log('Clicked!')}>Click Me</button>;
}

Follow-Up Questions​

  • How do anonymous functions differ from named functions?
  • Can you explain the difference between arrow functions and anonymous functions?

Source: greatfrontend/top-javascript-interview-questions