What is a typical use case for anonymous functions in JavaScript?

Answer

Anonymous functions in JavaScript are functions without a name, used when the function is temporary and doesn’t need to be reused. Common use cases include:

  1. Callbacks: For asynchronous operations or event handling (e.g., setTimeout or addEventListener).
setTimeout(function () {
  console.log('Callback executed');
}, 1000);
  1. Array Methods: For map, filter, reduce, etc.
const doubled = [1, 2, 3].map(function (num) {
  return num * 2;
});
  1. Event Listeners: Used for DOM events.
document.querySelector('#btn').addEventListener('click', function () {
  console.log('Clicked');
});
  1. IIFEs: For immediate execution and scope encapsulation.
(function () {
  console.log('IIFE executed');
})();
  1. Dynamic Assignment: Assigning inline functions to variables.
const greet = function () {
  console.log('Hello!');
};

For better debugging or reusable logic, named functions are preferred.

MDN Web Docs: Functions