Course contentsShow
← JavaScript
Lesson 433 of 2,72312. Higher-Order FunctionsFree lesson

Anonymous Functions in Practice

Using unnamed function expressions inline as arguments without assigning them to variables first.

Anonymous Functions in Practice

You'll learn how to use unnamed function expressions directly as arguments without storing them in variables first.

The Core Idea

Now that you understand functions are first-class values, you can write function expressions inline wherever you need them. Instead of creating a function, assigning it to a variable, then passing that variable, you can simply write the function expression directly in place.

Think of it like ordering food: you could write your order on a separate piece of paper (assign to a variable) and hand that paper to the waiter, or you could just tell the waiter directly (inline anonymous function). The result is the same, but the direct approach is faster when you only need to say it once.

Common Patterns

Immediately using a function without reuse:

// Instead of this:
const greeter = function(name) {
  return "Hello, " + name;
};
console.log(greeter("Sam"));

// Do this (anonymous function in practice):
console.log((function(name) {
  return "Hello, " + name;
})("Sam"));

Passing functions directly as arguments:

// Verbose way:
const callback = function() {
  console.log("Timer fired!");
};
setTimeout(callback, 1000);

// Anonymous in practice:
setTimeout(function() {
  console.log("Timer fired!");
}, 1000);

The anonymous function exists exactly where it's needed. No variable, no name, no extra line—just the logic right there.

When to Use This

Use anonymous functions inline when:

  • The function is simple and used only once
  • Naming it wouldn't add clarity
  • You want concise, focused code

This pattern is everywhere in JavaScript—especially with callbacks, event handlers, and array methods.

Key Takeaway: Anonymous functions shine when written directly where they're used, eliminating the need for temporary variables and keeping your code compact and readable.