Hi everyone,
I did the ‘School Catalog’ project (https://www.codecademy.com/courses/learn-intermediate-javascript/projects/school-catalog) from the ‘Classes’ class and faced a problem which hasn’t been dealed in the course…
It is asked:
Create a setter for
numberOfStudents
. The method should first check if the input (newNumberOfStudents
) is a number.
If it is a number, then set thenumberOfStudents
property. If not, log,'Invalid input: numberOfStudents must be set to a Number.'
I created this setter and it does nothing… If I create an instance of School or any subclass and put a string or other as argument for ‘numberOfStudents’ it still takes it…
I asked ChatGPT why it doesn’t work and he told me that the setter will only work if you attempt to reassign the value of the property. He advised the following:
So, if you want to enforce type checking when initially creating a
School
instance, you can add type checking logic in the constructor itself, like this:
So what is the point then to use a setter with a class constructor if it doesn’t check at the instantiation but at a property reassignment ? Is it a mistake in the instruction of the project ?
Thank you all for your enlightment !