1

Consider the following operation:

typeof (1 + undefined) => "number"

and now this operation:

isNaN(1 + undefined) => true

typeof states that the result of (1+undefined) should be a number.

While, the operation of if (1+undefined) is not a number is true.

How is this possible?

NOTE: I tested this in console of google chrome if that matters.

abhiox
  • 176
  • 1
  • 2
  • 12

3 Answers3

0

The answer is simple: NaN is a number.

The term "not a number" doesn't mean "not a member of the type number in JavaScript". It's a term from the relevant floating-point specification, in which a set of bit patterns is collectively used to designate values that are "not numbers"; that is, the bit patterns are not valid.

It's somewhat unfortunate that JavaScript was designed such that certain operations that have numerically meaningless results yield NaN, since the point of NaN in the spec is to designate values to be avoided. It's too late to revisit that decision however.

The global isNaN() function always attempts to convert its argument to number before performing the test. Thus, it's often used to check if a string value contains digits that can be interpreted as a valid number.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

Because typeof (1 + undefined) is typeof NaN, and

typeof NaN === "number" //true
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

Since (1 + undefined) result in NaN you get that behaviour. Check the examples below:

var value = 1 + undefined;
console.log('value for (1 + undefined) is ' + value);

var result1 = typeof (1 + undefined);
console.log('typeof (1 + undefined) is ' + result1);

//this result2
var result2 = isNaN(1 + undefined);
console.log('result of isNaN(1 + undefined) is ' + result2);

//is same as 
result2 = isNaN(NaN); //as 1 + undefined is NaN
console.log('result of isNaN(NaN) is ' + result2);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62