Callbacks

Functions as Arguments

Lesson 81
+30 XP
Step 1 of 5

What Are Callbacks?

A callback is a function that you pass as an argument to another function. The callback function is then executed at a later time, often after something completes.

Key Concept: Callbacks allow you to write flexible, reusable code by passing behavior (functions) as data.

Simple Example:

function greet(name) {
  return `Hello, ${name}!`;
}

function processUser(name, callback) {
  // Call the callback function with the name
  let message = callback(name);
  console.log(message);
}

// Pass greet as a callback
processUser('Alice', greet);  // Outputs: Hello, Alice!

Why Use Callbacks?

  • Execute code after an operation completes
  • Handle asynchronous operations (timers, events)
  • Create flexible, reusable functions
  • Respond to user actions or data changes