Skip to content
Advertisement

Break on NaN in JavaScript

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement