FAQ: Advanced Objects - Getters

In its simplest form, a getter will return the value of the backing property.

obj = {
  _prop: 'value',    //  backing property
  get prop () {
    return this._prop;
  }
}

The advantage of the getter is that we may impose conditions or custom formatting before returning a value. Say for instance the stored value is a float with a long decimal sequence. We could impose a minimum number of decimal places, and/or a maximum on the value we return from the getter.

    get prop () {
      const x = this._prop % 1;  //  extract the decimal fraction
      if (x.toString().length) > 6) {
        return Number(this._prop.toFixed(6))
      }
      return this._prop;
    }

Not sure how good an example this is, but you get the idea.


Rounding in JS

Rounding Decimals in JavaScript

This works too without Get, so i don’t understand why are we using get ?

A bit confused. I couldn’t pass the second question, so I checked my code against solution and the only difference was I didn’t put number in quotes. I’m confused though, doesn’t using quotes for number turn it into a string and make it meaningless to typeof? (obviously it doesn’t, that’s just what I expected to happen but you get my meaning). A bit like putting true or false in quotes?

What am I missing. (here’s my code and thanks etc)

Gosh, I spent half hour triple checking each piece of my code before I actually got this DOT.

1 Like

I could be wrong but try placing the return statement before the whole line of code

typeof always returns a string

1 Like

I was playing with the code then notice this. Can anyone explain why console.log in this scenario prints out an ‘undefined’ value?

const robot = {
_model: ‘1E78V2’,
_energyLevel: 100,
get energyLevel(){
if (typeof this._energyLevel === ‘number’){
console.log (My current energy level is ${this._energyLevel});
} else {
return (‘System malfunction: cannot retrieve energy level’);
}
}
}

console.log(robot.energyLevel);

//My current energy level is 100
undefined

Because return is not used, but console.log() instead, the default return value of the method is undefined. You are then logging the return value.

const log(x) {
  console.log(x)
}

console.log(log('defined'))
defined      // logged by the function
undefined    //  returned by the function by default
const log(x) {
  return x
}

console.log(log('defined'))
defined    //  returned by the function; logged at the caller

what is the get keyword use ?

const person = {
_firstName: ‘John’,
_lastName: ‘Doe’,
get fullName() {
if (this._firstName && this._lastName){
return ${this._firstName} ${this._lastName};
} else {
return ‘Missing a first name or a last name.’;
}
}
}
// To call the getter method:
person.fullName; // ‘John Doe’

is there any different if we omit the let keyword

get is used when the function is a getter function. Getter functions allow us to read the value of the property they are associated with without directly accessing the property itself. Using get fullName() rather than fullName(), we access the full name of the person as a property (person.fullName) rather than a function (person.fullName()). See the documentation here for more information.

1 Like

can i use interpolation in step 2 of this exercise?

What might that step be? Please post a link to the exercise page.

Why do we use getter when we can code like this. If doing so is simply omitting the parentheses, is it necessary?

The .eL() method is a method without getter

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'
    }
  },
  eL () {
    if (typeof(robot._energyLevel)==='number') {
      return `My current energy level is ${robot._energyLevel}`
    } else {
      return 'System malfunction: cannot retrieve energy level'
    }
  }
};

//console.log(robot._energyLevel.typeof())\
console.log(robot.energyLevel)
console.log(robot.eL())

Getters and setters in JS are syntactic sugar to give it a little more of an OOP feel as well as the functionality they offer. There is a good use for them, but as learners we may not find that obvious. Give it time and commit to learning how to implement them in such a way as to gain an advantage. That will come with practice.

https://www.codecademy.com/paths/front-end-engineer-career-path/tracks/fecp-javascript-syntax-part-ii/modules/fecp-learn-javascript-syntax-objects/lessons/advanced-objects/exercises/getters

sorry about that

We can see no reason why not to use interpolation since it is designed for just such a case. Be sure to use back ticks on the whole string, and write the variable (or expression) inside the ${} template. Note that the instructions ask us to return the string, not log it in the function.

1 Like