FAQ: Advanced Objects - Getters

Leave function body blank for now.

That would explain it. You’ve jumped ahead to the next step.

1 Like

In the Getters explanation codes, why the ternary expression doesn’t work (resulted ‘undefined’)?

For example:
… (codes start here)
get fullName() {
if (this._firstName && this._lastName){
return ${this._firstName} ${this._lastName};
} else {
return ‘Missing a first name or a last name.’;
}
}

Replacing with :
this._firstName && this._lastName ? ${this._firstName} ${this._lastName}: ‘Missing a first name or a last name.’;

person.fullName; // --> undefined

Sorry, my bad!
It should have been:
return (this._firstName && this._lastName)?${this._firstName} ${this._lastName}: ‘Missing a first name or a last name.’;

const robot = {

_model: ‘1E78V2’,

_energyLevel: 100,

get energyLevel() {

if (typeof this._energyLevel === isNaN){

  return `System malfunction: cannot retrieve energy level`; 

}else {

 return `My current energy level is ${this._energyLevel}`;

}

}

};

console.log(robot.energyLevel);

if I’m going to write my if statement like this and change the output like so.
Is this going to cause me a problem later on or I can do it like this??

There is no type isNaN. That is a global function to test for NaN.

The type we would want to check against is 'number'.

is there a reason why template literals were used in your first return statement Andrew?

Hi mtf,

can one use conditional operators in get statements ? if so what am I missing in below:

We cannot have statements of any kind inside an object unless they are inside a method. That means no let and definitely no, =.

I have checked this code and you are missing closing } curly bracket.

1 Like