.push to property or getter?


#1

A lesson in Classes, Inheritance V tells you to push a new certificate for a nurse to ‘certificates’.

Is it correct to push it to a getter rather than the actual property _certificates? If so, why?

Thanks for the clarification!

Lesson for reference: https://www.codecademy.com/courses/learn-javascript-classes/lessons/classes/exercises/inheritance-v


#2

you can’t .push() inside the getter method. You need to create a method named addCertification to push to the array.

getter is only called when you read a property, so there is no way to pass a value to the getter for push. You could use a setter, but the exercise decides to use a method. Both are viable ways to achieve this


#3

Edit: didn’t read your whole response. So why does .push to a getter work in my example below?

Sorry, should have clarified. It’s already in a function, which looks like this:

addCertification(newCertification) {
    this.certifications.push(newCertification);
  }

Why do we use this.certifications instead of this._certifications? As certifications is a getter, not a property.

PS - we seem to be in the same time zone, you answered my last question!


#4

no, certifications is the property. the underscore is only a naming convention to indicate this property implements getter and/or setter.

this.certifications will call the getter method to get the value, once the value is retrieved (returned by the getter method), .push() is being called to add a value to the property.

the getters only job is to read the property value.


#5

Ahhh so the underscore is ignored?

Edit: if so, that makes getters and setters make sense to me now!


#6

yes, except when you use the property inside the getter or setter method, then you need to include the underscore (just a syntax thing)

in the last step:

console.log(nurseOlynyk.certifications)

you log the property to the console, again, the getter is called.

lets say we have this:


class Nurse extends HospitalEmployee {
  constructor(name, certifications) {
    super(name);
    this.certifications = certifications;
  } 
  addCertification(newCertification) {
    this.certifications.push(newCertification);
  }
}

this.certifications would still need to read/get the value before we can add to it, the getter method just gives you additional control.