Passing Functions as Arguments
You'll learn how to hand one function to another as a parameter, unlocking callback patterns and flexible code design.
The Core Idea
Because functions are first-class values in JavaScript, you can pass them into other functions just like you'd pass a number or string. The receiving function can then call the passed-in function whenever it needs to. This is called a callback pattern — the function you pass gets "called back" by the outer function.
Think of it like giving someone a recipe card. You're not cooking the meal yourself; you're handing the instructions to someone else who will follow them when the time is right.
How It Works
function greet(name) {
return "Hello, " + name;
}
function processUser(userName, callback) {
const result = callback(userName);
console.log(result);
}
processUser("Alice", greet); // "Hello, Alice"
Here, greet is passed as the callback parameter. Inside processUser, we invoke it by calling callback(userName).
Why This Matters
function double(n) {
return n * 2;
}
function triple(n) {
return n * 3;
}
function transform(value, operation) {
return operation(value);
}
console.log(transform(5, double)); // 10
console.log(transform(5, triple)); // 15
The same transform function works with any operation. You've made your code reusable and flexible by letting the caller decide what action to take.
Key Takeaway: Passing functions as arguments lets you write flexible, reusable code where the caller controls behavior by providing different functions.