Passing Configuration Objects
What You'll Learn
You'll learn how to make factory functions more flexible by accepting a single configuration object instead of multiple individual parameters.
Why Configuration Objects?
As your factory functions grow, they often need more and more parameters. A function like createUser(name, age, email, country, premium, theme) becomes hard to use—you must remember the exact order, and optional values require passing undefined placeholders.
The solution: Pass one configuration object with named properties instead.
How It Works
Instead of many separate parameters, accept a single object and destructure or access its properties:
// Instead of many parameters in a fixed order:
function createUserOldWay(name, age, email, premium) {
return {
name: name,
age: age,
email: email,
premium: premium
};
}
// Use a configuration object:
function createUser(config) {
return {
name: config.name,
age: config.age,
email: config.email,
premium: config.premium || false
};
}
const user = createUser({
name: 'Alice',
email: 'alice@example.com',
age: 30
// premium omitted, will default to false
});
Benefits
- Named arguments:
{ premium: true }is clearer thantruein the 4th position - Order doesn't matter: Properties can appear in any sequence
- Easy defaults: Check for missing properties and provide fallbacks
- Extensible: Add new options without breaking existing calls
Key Takeaway: Passing a single configuration object to factory functions makes them easier to use, maintain, and extend as requirements grow.