anonymous function in JavaScript

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!");
});

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *