Why is line "num - num === 0" needed?
If simply true is returned, input NaN (not a number) will also return true. It turns out typeof NaN is number. Also NaN - NaN is NaN so this expression num - num === 0 returns true only when num is a number except NaN.
Yeah. And same goes for Infinity and -Infinity.
Ambar explained it pretty well.
I think the best, and easiest way, to check if a variable is of type 'number' in JS, is to use the
Number.isFinite(num)
method.
It will weed out anything that is not a number, including NaN and Infinity.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Why is line "num - num === 0" needed?
If simply true is returned, input NaN (not a number) will also return true. It turns out typeof NaN is number. Also NaN - NaN is NaN so this expression num - num === 0 returns true only when num is a number except NaN.
Yeah. And same goes for Infinity and -Infinity.
Ambar explained it pretty well.
I think the best, and easiest way, to check if a variable is of type 'number' in JS, is to use the
method.
It will weed out anything that is not a number, including NaN and Infinity.