An anonymous function in JavaScript is a function without a name.
Itβs usually used when a function is needed only once, such as in callbacks, event listeners, or immediately invoked functions.
β‘ Example:
// Anonymous function assigned to a variable
const greet = function() {
console.log("Hello, PC!");
};
greet(); // Output: Hello, PC!
π‘ Example in Callback:
setTimeout(function() {
console.log("Executed after 2 seconds");
}, 2000);
Here, the function has no name, and itβs executed after 2 seconds β perfect for short, one-time tasks.
π Arrow Function (Modern Anonymous Function)
setTimeout(() => {
console.log("This is an arrow anonymous function");
}, 1000);
Arrow functions are just shorter syntax for anonymous functions.
π§ Key Points:
- No function name (defined inline).
- Commonly used for callbacks, IIFE, and event handlers.
- Can be assigned to variables or passed as arguments.
- Cannot be reused elsewhere (unlike named functions).
π Example: Event Listener
document.getElementById("btn").addEventListener("click", function() {
console.log("Button clicked!");
});