isNaN('Hello World!') vs isNaN('')

Viewed 202

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.

4 Answers

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)

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.

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

Related