Reputation: 3626
I am going to write some Maths expressions in JS and wondered:
typeof(Infinity) // "number", in Maths it is NOT a number
typeof(NaN) // "number", how NaN (Not A Number) can actually be a number?
And just a few more experiments:
Infinity === Infinity // TRUE
Infinity * 2 === Infinity * 5 // TRUE, so 2===5 if Infinity !== 0?
However, this makes sense to me:
NaN * 2 === NaN * 5 // FALSE
Upvotes: 0
Views: 220
Reputation: 91
There's an answer about inequality of two NaNs here - Why is NaN === NaN false?. As for the infinities, this is a pure math - infinity times anything is infinity. Lastly, typeof returns "number" for Infinity and NaN just because these are constants of numeric type in JS.
Upvotes: 1
Reputation: 1074218
Why JS is designed so? Was there a particular reason for that?
JavaScript takes both NaN
(including the fact that it's never equal to itself) and infinity directly from IEEE-754, the go-to standard for floating point numbers in computing, which is also used by many other languages. (Specifically, it uses a "quiet NaN".) IEEE-754, in turn, gets a lot of this from mathematic theory (e.g., Infinity + 1
=== Infinity
, apparently this is considered true for some kinds of numbers, but I am not a mathematician; I would assume the designers of the standard had a reason for following that definition).
Are there potentials threats when writing Maths expressions in JS?
I wouldn't call them threats, but: NaN
will propagate throughout any calculation where it comes up. Other than that, you have the usual issues with precision discussed in this question and its answers.
Upvotes: 2