2

I would like to know why the following program behaves differently though the datatype is a string,

console.log(isNaN('Hello World!'))

console.log(isNaN(''))

Console shows the following result,

true

false

I expected both the result to be true.

Anyone help me to understand this basic thing.

Thank you.

Rafael
  • 499
  • 1
  • 3
  • 12
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN `Confusing special-case behavior` – mjwills Sep 09 '20 at 06:19
  • try `+'Hello World!'` vs `+''` ... coercion can cause confusion - also ... `isNan('1')` is false ... yet `'1'` is a string ... – Jaromanda X Sep 09 '20 at 06:21

4 Answers4

4

According to the documentation:

Since the very earliest versions of the isNaN function specification, its behavior for non-numeric arguments has been confusing. When the argument to the isNaN function is not of type Number, the value is first coerced to a Number. The resulting value is then tested to determine whether it is NaN. Thus for non-numbers that when coerced to numeric type result in a valid non-NaN numeric value (notably the empty string and boolean primitives, which when coerced give numeric values zero or one), the "false" returned value may be unexpected; the empty string, for example, is surely "not a number." The confusion stems from the fact that the term, "not a number", has a specific meaning for numbers represented as IEEE-754 floating-point values. The function should be interpreted as answering the question, "is this value, when coerced to a numeric value, an IEEE-754 'Not A Number' value?"

You may want to use Number.isNaN instead of isNan, it behaves differently (this is also mentioned in the link I provided)

Pavel Botsman
  • 773
  • 1
  • 11
  • 25
4

console.log(isNaN('')); 
// false: the empty string is converted to 0 which is not NaN

console.log(isNaN(' ')); 
// false: a string with spaces is converted to 0 which is not NaN

For more details, please refer to official documentation : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

mplungjan
  • 169,008
  • 28
  • 173
  • 236
sidverma
  • 1,159
  • 12
  • 24
1

As indicated in this

This function (isNanN()) returns true if the value equates to NaN. Otherwise it returns

The global isNaN() function, converts the tested value to a Number, then tests it.

When you converrt the given values to number you obtain this

Number("") = 0 
Number("Hello World!") = NaN

That explain the obtaining results.

Taoufik
  • 196
  • 1
  • 1
  • 12
-2

isNaN interprets empty string as 0 and that makes isNaN('') give true and for a string isNaN('abc') gives false because it is not a number

Ahmad Suddle
  • 190
  • 7