Rolintocour
Rolintocour

Reputation: 3168

Typescript: test for Nan, null and undefined only

I like to use the !! in Javascript to ensure that a variable is set and that no error will be thrown.

However today I have a variable with 0 value that is valid for me. I need to ensure that it is not NaN nor undefined, is there really no short way to do it without the boring if (variable !== NaN && variable !== undefined?

If that may help, I am using angular.

Thx.

Upvotes: 5

Views: 8978

Answers (3)

AlexanderFSP
AlexanderFSP

Reputation: 662

const a = 'value';

if (isNaN(a) || a === null) {
    console.log('a is NaN or null, undefined');
} else {
    // business logic ;)
}

Handle null in addition, because isNaN(null) === false.

Upvotes: 6

Jose V
Jose V

Reputation: 1864

The correct way to check for undefined, null, NaN is

if(a == null || Number.isNaN(a)) {
  // we did it!
}

please notice the use of Number.isNaN instead of just isNaN. If you did use just isNaN then your check will not do what you want for values like strings or empty object

if(a == null || isNaN(a)) {
  // {} comes in because `isNaN({})` is `true`
  // strings that can't be coerced into numbers 
  // some other funny things
}

Read more at MDN

Upvotes: 2

uiTeam324
uiTeam324

Reputation: 1245

You can use isNan. It will return true for undefined and NAN value but not for ZERO.

const variable = undefined;

 if(isNaN(variable)){
   console.log('I am undefined / NAN'); 
 }else{
   console.log('I am something / zero');
}

Upvotes: 3

Related Questions