DEV Community

Discussion on: I just created my first NPM package. It ain't much but it's honest work

Collapse
 
milan997 profile image
milan997

Why is line "num - num === 0" needed?

Collapse
 
supercoww profile image
Ambar Mutha • Edited

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.

Collapse
 
ispoljari profile image
Ivan Spoljaric • Edited

Yeah. And same goes for Infinity and -Infinity.

Collapse
 
ispoljari profile image
Ivan Spoljaric • Edited

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.