-1

Is it possible to write something like:

 if( * === NaN){
          this = 0;  
        };

What I'm trying to do is catch any math or variables that calculate as NaN and make them equal to 0. I could write the same if statement for each time math is done but it would be messy and I was hoping there was a simple solution like this.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
D. Cantatore
  • 187
  • 12

3 Answers3

0

I don't think so, since as far as I know nothing is equal to NaN. However, you can take advantage of that and do:

if( * !== *){
      //code when * is NaN  
    };

And only a NaN will meet the condition. I read this is safer than just to use isNaN() .

Sergeon
  • 6,638
  • 2
  • 23
  • 43
0

You can do something like this

function convertIfNaN (x) {
    if (isNaN(x))
        return 0;
    else
        return x;
}
yitzih
  • 3,018
  • 3
  • 27
  • 44
0

You can use the isNaN function like so:

if (isNaN(x)) {
    // do something
}

The built in isNaN function will only check if the value can be coerced to a number. You can also write your own function to simply check for the value "NaN" like so:

function isNaN(x){
  return x !== x;
}
dalyhabit
  • 29
  • 4
  • I think this is the closest to what I was looking to achieve. It appears the simple clever code option doesn't really fit the situation and I just did a copy paste of a small if statement to check each time the variable would be used before it was used. Thanks! – D. Cantatore Aug 20 '16 at 19:28