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"?
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
.
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
)
- Let num be ToNumber(number).
So isNaN("12")
=> isNaN(12)
=> false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With