Here's the code to start with.
function person(name, age, child){
this.name = name;
this.age = age;
if(this.child == undefined){
this.child = 'default';
}else{
this.child = child;
}
}
var sarah = new person('sarah',34,true);
document.write(sarah.child+' ');
So I'm trying to make an optional property inside a constructor function. But whatever I put inside the child parameter it always says 'default' when printed out. I am exceedingly new to JS, just came off php. No idea why this isn't working. I've looked at other questions, tried to follow, but what I try from them doesn't seem to help.
this.childis always undefined, since you did not define it (you only definedthis.nameandthis.age). Btw, you should use===to compare withundefined.child:if (child == undefined) {.childis the parameter (variable).this.childis a property.this.childis a property of the instance, which is alwaysundefinedbefore you define it. And you are only defining it later inside if check.