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