I use Chrome browser 60.x, and test the code isNaN([3])
.
The result is false
, but I cannot understand it.
[3]
is an Array, and it is not empty.
I think [3]
is array object, and it is not an number.
Otherwise the result of isNaN(["ABC"])
is true
.
And another result of isNaN([1,2,3])
is true
.
So I guess javascript engine is force changing array to number which the array has a single element.
Please let me know what is happened isNaN
function for array parameter.
ref1: Why is isNaN(null) == false in JS?
ref2: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
[EDIT] Thank you everyone for answering.
I understand javascript parsed the value implicitly before comparison.
And I found a useful link while reading Nina Scholz's answer.
The comparison table : http://dorey.github.io/JavaScript-Equality-Table/
Example. The isNaN(null) == false is semantically correct. This is because null is not NaN.
The isNaN() function determines whether a value is NaN or not.
JavaScript isNaN() Function The isNaN() function is used to check whether a given value is an illegal number or not. It returns true if value is a NaN else returns false.
isnan() isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number.
When you use isNaN
it tries to parse your input value into the number
and then checks if it is NaN
or not.
See some examples.
For an array with one item, the Number()
function returns an object, which actually hold the first item as a value (see console.log
). For many items it returns NaN
, so you get isNaN
's result -> true
.
const a = new Number([3]);
console.log(`a is ${a}`);
console.log(`isNaN(a) - ${isNaN(a)}`);
const b = new Number([3,4,5]);
console.log(`b is ${b}`);
console.log(`isNaN(b) - ${isNaN(b)}`);
According to the rules for equality comparisons and sameness, the array is converted, first with toString
and then to a number for checking.
console.log(isNaN([3]));
console.log(isNaN('3')); // convert with toString to a primitive
console.log(isNaN(3)); // convert to number
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