Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does isNAN("12") evaluate to false?

Tags:

javascript

Why does JavaScript interpret 12 and "12" as equal?

function sanitise(x) {
  if (isNaN(x)) {
    return NaN;
  }
  return x;
}

var a = "12"
var b = 12
console.log(typeof(a))
console.log(sanitise(a));
console.log(sanitise(b));

Output:

> "string"
> "12"
> 12

And then, what is the difference between "12" and "string"?

like image 719
bytefish Avatar asked Jan 08 '18 11:01

bytefish


2 Answers

The isNaN() function determines whether a value is NaN or not.

As per documentation, NaN values are generated when arithmetic operations result in undefined or unrepresentable values. Such values do not necessarily represent overflow conditions. A NaN also results from attempted coercion to numeric values of non-numeric values for which no primitive numeric value is available.

For example, dividing zero by zero results in a NaN — but dividing other numbers by zero does not.

Here "12" is not a number but it is not NaN either. Therefore isNaN() returns false.

Also, 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.

Therefore isNaN('s') returns true as 's' is converted to a number. Parsing this as a number fails and returns NaN.

like image 150
Rohit Agrawal Avatar answered Oct 02 '22 10:10

Rohit Agrawal


why “12” is a not NaN in JavaSciprt?

As per spec, there is an implicit conversion toNumber before checking if the given input is a number or not (or Not a Number - NaN )

  1. Let num be ToNumber(number).

So isNaN("12") => isNaN(12) => false

like image 38
gurvinder372 Avatar answered Oct 02 '22 11:10

gurvinder372