Anonymous Functions in JavaScript

📍 What is an Anonymous Function?

An anonymous function is a function without a name. Unlike named functions, these are usually used where the function doesn’t need to be reused — like in callbacks or immediately invoked function expressions (IIFEs). 🧩

>>“Not every hero wears a name — some just get things done.”

🔤 Syntax

Anonymous Function

function() {
  // code block
}

Note

💡 Anonymous functions are often written as function() or using arrow function syntax () => .

🧪 Example: Assigned to a Variable

Assigning an Anonymous Function

const greet = function(name) {
  return "Hello, " + name + "!";
};

console.log(greet("Alice")); // Hello, Alice!

The function has no name, but is assigned to the variable greet.

🌀 Example: As a Callback

Anonymous Function as Callback

setTimeout(function() {
  console.log("This runs after 2 seconds");
}, 2000);

Here, the anonymous function is passed directly into setTimeout() as a callback. 🔁

⚡ Arrow Function Equivalent

Arrow Function Version

setTimeout(() => {
  console.log("Arrow function callback");
}, 1000);

Note

✅ Arrow functions are anonymous by nature — perfect for short, inline callbacks.

🎯 Use Cases

  • Callback functions (e.g., setTimeout, map, filter)
  • Immediately Invoked Function Expressions (IIFE)
  • Short-lived tasks where reuse is not required

🚀 IIFE (Immediately Invoked Function Expression)

Anonymous IIFE

(function() {
  console.log("This runs immediately!");
})();

This anonymous function executes as soon as it's defined — often used to create a private scope.

⚠️ Drawbacks

  • No function name means harder debugging and stack traces
  • Can reduce code readability if overused

✅ Summary

  • Anonymous functions have no name
  • They’re useful in callbacks, short operations, and IIFEs
  • Often written as function expressions or arrow functions
  • Powerful, but best used with care for maintainability 👨‍💻

📚 References

>>“A function with no name, yet infinite power in the right place.” 🔥