Is there any modern browser that raises exceptions on NaN propagation (ie multiplying or adding a number to NaN), or that can be configured to do so?
Silent NaN propagation is an awful and insidious source of bugs, and I'd love to be able to detect them early, even at a performance penalty.
Here's an example bug that use strict
, jshint
et al. wouldn't pick up:
object = new MyObject(); object.position.x = 0; object.position.y = 10; // ... lots of code var newPosition = object.position + 1; // <- this is an error, and should // have been object.position.x // however it fails *silently*, // rather than loudly newPosition *= 2; // <- this doesn't raise any errors either. // this code is actually ok if the // previous line had been correct
Note: The TypeScript compiler is able to detect errors like the above, even in JS code, if type inference succeeds.
In this article, we will convert the NaN to 0. Using isNaN() method: The isNan() method is used to check the given number is NaN or not. If isNaN() returns true for “number” then it assigns the value 0. Using || Operator: If “number” is any falsey value, it will be assigned to 0.
Although either side of NaN===NaN contains the same value and their type is Number but they are not same. According to ECMA-262, either side of == or === contains NaN then it will result false value.
The opposite of isNaN is ! isNaN , reads like: "isn't not a number" therefore, it's a number.
In JavaScript, NaN is short for "Not-a-Number". In JavaScript, NaN is a number that is not a legal number. The Global NaN property is the same as the Number.
To answer the question as asked:
Is there any modern browser that raises exceptions on NaN propagation (ie multiplying or adding a number to NaN), or that can be configured to do so?
No. Javascript is a very forgiving language and doesn't care if you want to multiply Math.PI
by 'potato' (hint: it's NaN
). It's just one of the bad parts (or good parts, depending on your perspective) about the language that us developers have to deal with.
Addressing the bug that has you asking this question (presumably), using getters and setters on your Objects is one solid way to enforce this and also keep you from making mistakes like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With