Getters and setters 1 -- clarification?


#1

exercise link: https://www.codecademy.com/courses/learn-javascript-objects/lessons/objects/exercises/getters-setters?action=resume_content_item&course_redirect=introduction-to-javascript

my code:

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

};

  1. why is
if(typeof ageIn === "number") 

wrong? In this case its the use of " " instead of ’ '. I thought ’ ’ and " " were the same? like just preference based?

  1. i put in
ageIn = this._age;

instead of

 this._age = ageIn;

and want to know why that is wrong. I think its most similar to “a=b” and “b=a” where the logic is the same but its just written differently?


#2

In written math, a + b = c and c = a + b are equivalent expressions. but in programming that is not the case. Assignment is always right to left, so we can only write, c = a + b.

Likewise, we must write, this._age = ageIn for the parameter to be assigned to the attribute.

Remember to always write a getter if you have a setter, else the setter does not work.

As far as quotes are concerned, either single or double are both valid. Internally they are all treated as single. The SCT may have been written to accept only one form or the other, so we just have to go along with that.

Technically, now that we have ES6+ and template strings that use backticks, we can use them in most cases and not use ordinary quotes at all (or almost). If you use them and it throws errors, then make a note of the situation so you remember when NOT to use backticks.


#3

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