In the ‘Advanced Objects’ lesson, I just finished the exercise about getter methods.
So far, I don’t see the use of the ‘get’ keyword.
The example from this page shows:
const robot = {
_model: '1E78V2',
_energyLevel: 100,
get energyLevel() {
if (typeof this._energyLevel === "number"){
return `My current energy level is ${this._energyLevel}`;
} else {
return 'System malfunction: cannot retrieve energy level'
}
}
};
console.log(robot.energyLevel);
But it seems to work exactly the same if I code it like this:
const robot = {
_model: '1E78V2',
_energyLevel: 100,
energyLevel() {
if (typeof this._energyLevel === "number"){
console.log(`My current energy level is ${this._energyLevel}`);
} else {
console.log('System malfunction: cannot retrieve energy level');
}
}
};
robot.energyLevel();
When would I want to use the first approach when the second is more readable?