In JavaScript, anonymous functions are functions that are defined without a name. They are often used as arguments to other functions or assigned to variables.
Syntax:
An anonymous function can be defined using the function
keyword, or using arrow function syntax (ES6+).
- Traditional anonymous function:
const myFunction = function() { console.log("This is an anonymous function"); }; myFunction();
- Arrow function (ES6+):
const myFunction = () => { console.log("This is an anonymous arrow function"); }; myFunction();
Common Use Cases:
- Callbacks: Anonymous functions are often passed as callbacks to functions.
setTimeout(function() { console.log("Executed after 2 seconds"); }, 2000);
- Event Handlers: Anonymous functions can be used as event listeners.
document.getElementById("myButton").addEventListener("click", function() { alert("Button clicked!"); });
- Immediately Invoked Function Expressions (IIFE): An anonymous function that is executed as soon as it is defined.
(function() { console.log("This is an IIFE"); })();
Key Characteristics:
- No name: Unlike regular functions, anonymous functions are not named when they are defined.
- Can be assigned to variables: They can be stored in variables and invoked using the variable name.
- Flexible: Anonymous functions are particularly useful in functional programming patterns like higher-order functions, callbacks, or event handling.
Benefits:
- Helps reduce code verbosity.
- Enables dynamic behavior with functions that are used only once or in specific contexts.
- Useful in scenarios where functions don’t need to be reused.