Results 1 to 2 of 2

Thread: Javascript Version of quiet_NaN()?

Hybrid View

  1. #1
    Join Date
    Feb 2006

    Javascript Version of quiet_NaN()?

    Some background:
    I write numerical programs.
    I usually write them in C++ and then translate them to JavaScript for posting on a web page.
    In C++, I like to initialize variables to NaN using the C++ function quiet_NaN().
    That way, if a user misses the error message indicating not all results are valid, he will hopefully notice the NaN numbers when the results are output. It acts like a double back-up.
    I mean, if he sees output like the following, he should note that something is wrong and go back to check the inputs, or the program, or know that results could simply not be computed.
    My question: is there a JavaScript equivalent of quiet_NaN()?

    Let's say I have a one-dimensional array of type double variables, 1000 entries long, called ResultArray.
    I would like to take C++ code similar to the following

    // Initialize all entries of this array to NaN
    for (var i = 0; i < 1000; i++){
     ResultArray[i] = std::numeric_limits<double>::quiet_NaN();
    and create similar code in Javascript.

    Can this be done? If so, how?

  2. #2
    Join Date
    Jul 2013
    You can just assign it:

    var resultArray = [];
    for( var i = 0; i < 1000; i++ ) {
        resultArray[i] = Number.NaN;
    In fact, it could even be only resultArray[i] = NaN, though I personally like the static access to show where it comes from. The reason why it exists both as a property of Number and as a property of the global object is somewhat "historical", you can read it up on the Mozilla MDN. One note to make is that you can never compare a value against either NaN or Number.NaN, as it will always return false (in fact, any === comparison of NaN and Number.NaN will return false). Use Number.isNaN (or isNaN) instead.

    Though I don't think there is a reason to do any of this. By not doing this, you will leave the value as undefined, which is perfectly fine for computational purposes. And if you want it to be NaN for visual purposes, just adapt the output part of your script to map undefined values to Number.NaN. You could also simply deny any output and just display the error message – if there is nothing but the message, I'm sure any user will notice something is wrong.
    Last edited by Airblader; 09-06-2013 at 07:17 PM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center