Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isNaN([3]) is false in JavaScript?

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/

like image 284
IvoryCirrus Avatar asked Sep 04 '17 06:09

IvoryCirrus


People also ask

Why isNaN of null is false?

Example. The isNaN(null) == false is semantically correct. This is because null is not NaN.

What does isNaN () in JavaScript do?

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

What does isNaN 345 function returns false true undefined?

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.

What does isNaN returns if value is Not-a-Number?

isnan() isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number.


2 Answers

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)}`);
like image 87
Suren Srapyan Avatar answered Sep 22 '22 19:09

Suren Srapyan


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
like image 34
Nina Scholz Avatar answered Sep 22 '22 19:09

Nina Scholz