Getters and Setters I


#1

Why the correct version of the code requires both ‘console.log’ and ‘return’ one after another within Else brackets.Especially when the example code with the restaurant has only the ‘console.log’ there?

Here is code:

let person = {
_name: ‘Lu Xun’,
_age: 137,

set age(ageIn) {
if (typeof ageIn === ‘number’) {
this._age = ageIn;
}
else {
console.log(‘Invalid input’); //Why this is here with
return ‘Invalid input’; // this?
}
}

}


#2

Getters and Setters I

If the input is a number, set the _age property to the input value. If the input is not a number, return the string, ‘Invalid input’.

There is no indication that we are to log the string, only return it.

But it does beg another question… What happens to the return value?

Try this in the lesson interface…

  set age(newAge) {
    if (typeof newAge === `number`) {
      this._age = newAge;
    } else {
      console.log(`Invalid input`);    // this is the line to focus on
      //return `Invalid input`;
    }
  },

Now we call it with a strange bit of syntax…

console.log(person.age = `Thirty-nine`);

The output is…

Invalid input
Thirty-nine

No real point to make just yet, though. Adding a return value might change things…

  set age(newAge) {
    if (typeof newAge === `number`) {
      this._age = newAge;
    } else {
      console.log(`Invalid input`);
      return `Invalid input`;
    }
  },

Output,

Invalid input
Thirty-nine

This would clearly indicate that setters do not have return values (that we can make use of) other than what we send them. They are closely knit with their context counterpart, set age() => this._age, etc.

The moral of the story would seem to be that there is no point having a return statement, so just what the author intended by having us return the string rather than log it may never be known. Bit of a white elephant when it’s out in open.

Once you pass the lesson, amend your code to what makes the most sense to you. It won’t affect your progress. Be sure to Run so it gets saved.


#3

Thank you @mtf for your prompt response!


#4

You’re welcome.

Here is the setter I eventually settled upon…

  set age(newAge) {
    if (+newAge > 0) {
      this._age = newAge;
    } else {
      console.log(`Invalid input`);
    }
  },

The unary operator, +, attempts to convert its operand to a number, and failing that will yield NaN, which by itself will fail. I added the greater than zero so the number has to be absolute.


#5

Extra Study

Getters and Setters deserve to be treated in a world of their own. Getters should be just that, the gopher that returns the corresponding property value. Setters are the reverse. They give a new value to their respective property.

  get name() {
    return this._name;
  },
  get age() {
    return this._age;
  }

Given a person instance,

console.log(`${person.name} is ${person.age} years old.`)
Lu Xun is 39 years old.

It’s easy to think of .age and .name as properties, but really they are not. They are methods that know how to find their respective properties (where the real data is stored). The above is the return of two method calls interpolated into an output string.

By leaving getters completely naked of any arbitrary dressing, they can be accessed by any part of the program and be expected to give a usable value. How that value is treated is up to that part of the program. Moral being, don’t dress up the returns of getters. Save that for the caller to address.

All this raises a question: Can we represent our instance in a single command without creating special methods? The answer is a positive, yes, with our own custom repr() method.

    repr() {
        return `${this.name} is ${this.age} years old.`
    }

Command,

console.log(person.repr());

Output,

Lu Xun is 39 years old.

Mind, this is rather sketchy. Best read up on it some more (as will I).

Notice that we are calling the instance methods, not the variables themselves. This is a great feature of getters.


In the end it comes down to this,

let person = {
  _name: `Lu Xun`,
  _age: 137,
  get name() {
    return this._name;
  },
  get age() {
    return this._age;
  },
  repr() {
    return `${this.name} is ${this.age} years old.`
  },
  set name(newName) {
    if (newName.toString()) {
      this._name = newName;
    } else {
      console.log(`Invalid input`);
    }
  },
  set age(newAge) {
    if (+newAge > 0) {
      this._age = newAge;
    } else {
      console.log(`Invalid input`);
    }
  }
};
console.log(person.repr());
person.age = 39;
console.log(person.repr());
person.name = `Lu Zi Xun`;
console.log(person.repr());

Output,

Lu Xun is 137 years old.
Lu Xun is 39 years old.
Lu Zi Xun is 39 years old.    // no offense; improvising

#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.