I'm looking to create a model in JavaScript. Here is an example of the code that I have so far:
// Person model
function Person(firstName, age) {
// Check first name
if (firstName) {
if (typeof firstName === 'string') {
this.firstName = firstName;
}
else throw new Error('The first name is not a string.');
}
else throw new Error('First name is a required field.');
// Check age
if (age) {
if (typeof age === 'number') {
if (age < 0) {
throw new Error('The age provided is a negative.');
}
else {
this.age = age;
}
}
else throw new Error('The age provided is not a number.');
}
else throw new Error('Age is a required field.');
}
// Example usage
try {
var joel = new Person('Joel', 30);
console.log(joel);
}
catch(err) {
console.log(err.message);
}
Is this an idiomatic approach to the solution? And if so is there a way in which I can improve it?