Default Parameter Values in Constructors
What you'll learn: How to give constructor parameters default values so your class instances work even when some arguments are missing.
The Core Idea
When creating instances of a class, you might not always want to require every single parameter. Default parameter values let you specify fallback values that kick in automatically when an argument is undefined or not provided at all. This is the same default parameter syntax you've used with regular functions, now applied inside your class constructor.
Think of it like ordering a coffee: if you don't specify milk preference, the barista uses regular milk by default. You can still customize it, but there's a sensible fallback ready.
How It Works
In your constructor method, use the = operator right in the parameter list to assign default values:
class User {
constructor(name, role = 'guest', active = true) {
this.name = name;
this.role = role;
this.active = active;
}
}
const admin = new User('Alice', 'admin', true);
console.log(admin.role); // 'admin'
const regularUser = new User('Bob');
console.log(regularUser.role); // 'guest' (default)
console.log(regularUser.active); // true (default)
const moderator = new User('Carol', 'moderator');
console.log(moderator.active); // true (default)
The defaults only apply when the argument is undefined or omitted entirely. If you explicitly pass a value (even null or false), the default is ignored.
Why This Matters
Default parameters make your classes more flexible and user-friendly. You can require the essential data (name in our example) while making optional properties convenient to work with. This reduces boilerplate and makes instance creation cleaner.
Key Takeaway: Default parameter values in constructors provide automatic fallback values for optional arguments, making your classes easier to use without sacrificing flexibility.