Link to project:
https://www.codecademy.com/courses/introduction-to-javascript/projects/school-catalog
Link to project walk-through video:
https://youtu.be/9p2VeKRKZ1Q
Step 5 in this project asks us to create a setter for numberOfStudents
, which also verifies that the input is a number. In the walk-through video, the suggested solution uses isNaN()
. I would like to raise some issues I’ve found with this and get some feedback:
- I think the video incorrectly uses
isNaN()
in theif
statement’s condition, as follows:
set numberOfStudents (value) {
if (value.isNaN()) {
console.log('Invalid input...');
} else {
this._numberOfStudents = value;
}
}
This results in an error as I don’t think isNaN()
can be used in this way, and it will get people confused e.g. https://discuss.codecademy.com/t/school-catalogue/411818/21?u=jon_morris. As @mtf also points out in this linked post, and as indicated in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Syntax, the correct use of isNaN()
should be:
isNaN(value)
-
However, on testing I’ve found some issues with using
isNaN(value)
in the above setter. Inputs of'10'
(a number as a string),null
,true
andfalse
all evaluate tofalse
, and are therefore incorrectly allowed. -
In his “Aside” in this post https://discuss.codecademy.com/t/setter-in-javascript-project-school-catalogue-not-doing-anything-please-help/348546/8?u=jon_morris, @mtf suggests using the unary operator
+
instead, as follows:
(He explains how this works in his post)
set numberOfStudents (value) {
if (+value) {
this._numberOfStudents = value;
} else {
console.log('Invalid input...');
}
}
On testing, this seems to be an improvement on using isNaN(value)
, as inputs of false
or null
evaluate to false
, and therefore now correctly log the Invalid input message. However, out of the values incorrectly allowed by isNaN(value)
, inputs of '10'
(a number as a string) and true
are still incorrectly allowed by +value
. In addition, the number 0
isn’t allowed (as this is evaluated as false
), although this isn’t really an issue, as in this particular use case we wouldn’t want numberOfStudents
to be set to 0
anyway.
- Using
typeof value === 'number'
as the condition avoids all of the issues described above withisNaN(value)
or+value
, and only number types are allowed. So, the following seems to me to be the best solution:
set numberOfStudents (value) {
if (typeof value === 'number') {
this._numberOfStudents = value;
} else {
console.log('Invalid input...');
}
}
Any thoughts and comments gratefully received