2

In Javascript, if we multiply a string with number we get NaN:

 console.log("manas" * 5); // result is NaN    

Why then does the following code result in false instead of true?

console.log("manas" * 5 == NaN)  // results false
Stephen Byrne
  • 7,400
  • 1
  • 31
  • 51
manas
  • 6,119
  • 10
  • 45
  • 56
  • Instead of padding out your text to bypass the quality filter, how about you actually *add in a question*? You managed to format the code just fine, it is the rest of your question body that is the problem here. – Martijn Pieters May 12 '15 at 07:02

5 Answers5

5

Use the isNaN function instead.

console.log(isNaN("manas" * 5));

http://www.w3schools.com/jsref/jsref_isnan.asp

NaN, not a number, is a special type value used to denote an unrepresentable value. With JavaScript, NaN can cause some confusion, starting from its typeof and all to the way the comparison is handled.

Several operations can lead to NaN as the result. Because there are many ways to represent a NaN, it makes sense that one NaN will not be equal to another NaN.

Alvin Magalona
  • 771
  • 3
  • 13
1

NaN is a special numeric value which is not equal to anything including itself. To properly test for NaN you need to use isNaN function.

From specification:

Returns true if the argument coerces to NaN, and otherwise returns false.

Here is also useful note from the same ECMAScript section:

A reliable way for ECMAScript code to test if a value X is a NaN is an expression of the form X !== X. The result will be true if and only if X is a NaN.

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself. Testing against NaN

ozil
  • 6,930
  • 9
  • 33
  • 56
0

Javascript is not that smart - when either side of the == operator is Nan, the whole thing evaluates as false (similar to how if leftside of || is false, it doesn't bother looking at right side)

So, even Nan == Nan will return false.

Here's a good article on Nan behaviour

http://ariya.ofilabs.com/2014/05/the-curious-case-of-javascript-nan.html

binderbound
  • 791
  • 1
  • 7
  • 27
0

In Javascript,

NaN == NaN    //always results false.

(self comparison of NaN to itself is always false in javascript)

refer:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN

also see Is NaN equal to NaN?

Community
  • 1
  • 1
Ram
  • 23
  • 4