Functions as Configuration
You'll learn how passing functions can replace hard-coded flags or options, making your code more flexible and powerful.
The Traditional Problem: Configuration Flags
When building reusable code, you often need to customize behavior. The naive approach uses boolean flags or string constants:
function processList(items, sortDescending) {
// If sortDescending is true, sort one way
// If false, sort another way
// What if you need alphabetic vs numeric sorting?
}
This quickly becomes messy—you'd need sortDescending, sortAlphabetic, sortNumeric, etc. Each new variation requires code changes.
The Solution: Pass Functions Instead
Instead of flags that dictate what to do, pass a function that does it:
function processList(items, sortFn) {
return items.sort(sortFn);
}
// Now callers configure behavior by passing different functions:
const ascending = (a, b) => a - b;
const descending = (a, b) => b - a;
processList([5, 2, 8], ascending); // [2, 5, 8]
processList([5, 2, 8], descending); // [8, 5, 2]
The processList function doesn't know or care how sorting works—it delegates that decision to the caller via sortFn.
Why This Works Better
- Unlimited flexibility: Any sorting logic works without changing
processList - Separation of concerns: The algorithm (process and sort) is separate from the policy (how to sort)
- No explosion of parameters: One function parameter handles infinite variations
Think of it like a restaurant: instead of having menu flags ("spicy: yes/no, salt: low/medium/high"), the chef accepts a seasoning function you provide.
Key Takeaway: Passing functions as configuration parameters lets you customize behavior without changing the algorithm itself, making code far more flexible than boolean flags ever could.