Callbacks & Higher-Order Functions
Quick Overview
Passing `fn` hands over the function; `fn()` hands over its result. That one pair of parentheses is the difference between scheduling work for later and having already run it.
Deep Dive
1. First-Class Functions
In JavaScript, functions are First-Class Citizens. This means functions can be treated like any other value: stored in variables, passed as arguments, and returned from other functions.
2. Why It Matters
A Higher-Order Function is a function that receives another function as an argument (a Callback) or returns a function. Higher-order functions enable asynchronous programming and custom utilities.
3. The Callback Pattern
function processUser(name, callback) {
const formattedName = name.trim().toUpperCase();
callback(formattedName);
}
// Passing an inline callback function
processUser(" alex ", function(result) {
console.log(`Processed User: ${result}`); // "Processed User: ALEX"
});
4. Asynchronous Callbacks
Callbacks allow code to run after an async operation completes (such as timer events or network data loads):
console.log("Start");
setTimeout(() => {
console.log("2 Seconds Elapsed");
}, 2000);
console.log("End");
5. Common Mistakes
- Callback Hell: Nesting multiple asynchronous callbacks inside callbacks creates unmaintainable "Pyramid of Doom" code. Promises solve this!
- Invoking Callback Instantly: Writing
processUser("Alex", callback())executescallbackimmediately instead of passing the function reference. Omit parentheses when passing callback function references:processUser("Alex", callback)!
6. Try It Yourself
Write it yourself. The tests below run against your code.
Process Name with Callback Function
Examples
7. Next Steps
Callbacks are the building blocks of async operations. Next, let's master the this keyword and function binding!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.