-4
console.log(typeof NaN)

The above returns 'number'.

Q1. How do I find a way around this?

Q2. What is a better way to find the type of a variable? (instead of typeof)

Thanks!

Update: Thank you for all your comments. But the first answerer understood my question. I was concerned about assessing the type of a return statement of 'NaN' to not show up as a 'Number'.

I was using typeof() in an if statement to act when if(typeof(x) == "number") { do this.. }

But the condition passed even though x was NaN. I wanted to resolve this.

I did not know 'NaN' was of type 'Number' cause NaN means 'Not a Number'. That led to confusion.

I apologize for not being clear on what I wanted to ask. But my issue is solved.

Thanks everyone!

Sunny Bharadwaj
  • 153
  • 1
  • 11

2 Answers2

0

If you want to check whether a number is not NaN, you may want to use isNaN function:

var val = 4

console.log(isNaN(val)) // false

var val2 = NaN

console.log(isNaN(val2)) // true

To check whether a variable contains a number and is not NaN You may then use the following:

typeof val === 'number' && !isNAN(val)
Mehdi
  • 7,204
  • 1
  • 32
  • 44
-2

Don't use typeof unless speed is a need it fails for both arrays and null. However according to the spec NaN is in fact of type Number.

Use

var getType = function (obj) {
    return Object.prototype.toString.call(obj).slice(8, -1);
};
arc.slate .0
  • 428
  • 3
  • 8