JavaScript Fundamentals / Functions

Anonymous Function

🟡 What is an Anonymous Function?

An anonymous function is a function that does not have a name.

It is usually stored in a variable, passed as an argument, or used inside other functions.

You cannot call it directly by name because it has none.


🧩 Why Use Anonymous Functions?

Anonymous functions are useful when:

  • You need a function temporarily.

  • You want to assign a function to a variable.

  • You want to pass functions as arguments (callbacks).

  • You’re writing short, one-time-use functions.


🟢 Example 1: Function Expression

  • The function has no name.

  • Stored in greet.

  • Called using the variable name.


🟢 Example 2: Anonymous Function as Callback

Here, the function is passed directly as an argument.


🟢 Example 3: Arrow Function (Short Anonymous Function)

Arrow functions are always anonymous.


🎗️ Key Points

  • Anonymous functions do not have names.

  • Mostly used in:

    • Callbacks

    • Event listeners

    • Function expressions

    • Arrow functions

  • Useful for short, temporary, or inline logic.

  • Aren’t hoisted like normal functions.