I don't understand how the setter works

Hello i’m having trouble with the setter methods.
For example i don’t understand why the console.log from my setter method doesn’t log when I write a string instead of a number when i call my function.
Can someone explain this to me ?

from MDN:

The set syntax binds an object property to a function to be called when there is an attempt to set that property.

you don’t set the numberOfStudents property anywhere?

I set it on my parent class School

set numberOfStudents(newNumberOfStudents) {
    if (typeof newNumberOfStudents === 'number')
    {
      this._numberOfStudents = newNumberOfStudents;
    } 
    else{
      console.log('Invalid input: numberOfStudents must be set to a Number.');
    }
  }

That is the definition/declaration of the setter. But you don’t set/assign the property any value anywhere.

Oh !
I thought it would check the property in the calling function

As you can read from the mdn documentation, doing set numberOfStudents will create/declare/define a numberOfStudents property, and bind a function to this property

this function is called when you assign (=) something to this property (numberOfStudents)

the assignment (=) part isn’t happening anywhere, so the function bound to the property is never called/executed

Ok, thank you for the reply, I guess I’ll have to read a bit more the documentation next time.

reading documentation is generally good advice.

Do you need more help still? I know exactly what the problem with your code is, but I am trying to guide you, which I think you will learn more from in the long run

1 Like

It’s ok thank you. I just deleted some code to make things more clear. I know what’s wrong.

1 Like