Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break on NaN in JavaScript

Tags:

javascript

nan

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.

like image 915
kibibu Avatar asked Dec 12 '13 04:12

kibibu


People also ask

How do you resolve NaN?

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.

Why is NaN === NaN false?

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.

What is the opposite of NaN in JavaScript?

The opposite of isNaN is ! isNaN , reads like: "isn't not a number" therefore, it's a number.

What is NaN in JavaScript?

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.


1 Answers

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.

like image 142
Rob M. Avatar answered Sep 25 '22 02:09

Rob M.