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