Settler


#1

Hello guys,

On Gettlers and Settlers 1

let person = {
  name: 'Lu Xun',
  age: 137,
  
  set age(ageIn) {
    if (typeof ageIn === 'number') {
      this._age = ageIn;
    }
    else {
      console.log('Invalid input');
      return 'Invalid input';
    }
  }

};
console.log(person._age);

why we used return in else statement? What is importance?


#2

There was another question a day or two ago along similar lines, and I wrote that we cannot use class syntax in a plain object (literal). Well, I will have to dig that topic up again because after playing with this one for a while I found what the problem was, and also that I was dead wrong.

Your object is missing a getter method, without which your age property becomes undefined.

let person = {
  name: 'Lu Xun',
  _age: 137,
  get age() {
    return this._age;
  },
  set age(ageIn) {
    if (typeof ageIn === 'number') {
      this._age = ageIn;
    }
    else {
      console.log('Invalid input');
      return 'Invalid input';
    }
  }
};
console.log(person.age);     //->  137
console.log(person._age);    //->  137

The setter and getter can be written in any order. A getter does not need a setter, but a setter needs a getter. Note that the underscore is used on the property to facillitate the methods.

return is used to break out of the function and send an error message back. There is no need to log the message in the function. Your last statement will log it.


#3

Can we please get a link to the exercise where this code is from? It would really help in preparing for the next wave of questions if we actually knew which lesson it was, and what is expected. Thanks.

NVM. Found it…

https://www.codecademy.com/courses/learn-javascript-objects/lessons/objects/exercises/getters-setters?action=lesson_resume


#4

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