I\'ve created a class and I would like to set some default options for values in case the user does not supply any arguments. I recently went from a constructor that took mu
Make sure you have a default for the object itself.
module.exports = class User {
constructor(options) {
options = options || {}
this.name = options.name || "Joe";
this.age = options.age || 47;
}
}
You could either set a default value for options, i.e {}
.
class User {
constructor(options = {}) {
this.name = options.name || "Joe";
this.age = options.age || 47;
}
}
or first check for options
to be truthy and then access the value.
class User {
constructor(options) {
this.name = options && options.name || "Joe";
this.age = options && options.age || 47;
}
}
If you want to change to a configuration pattern, you can still keep your default parameter syntax:
module.exports = class User {
constructor({ name = "Joe", age = 47 } = {}) {
this.name = name;
this.age = age;
}
}
const User = require("./user");
const user = new User(); // Defaults to "Joe" and 47
You actually just need a oneliner:
const defaultUser = {
name: "Joe",
age: 47
};
module.exports = class User {
constructor(options) {
Object.assign(this, defaultUser, options)
}
}