igorpavlov - 1 year ago 67

Javascript Question

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`

- Why JS is designed so? Was there a particular reason for that?
- Are there potentials threats when writing Maths expressions in JS?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**