1

So, I have the following issue:

let str = "M1"
console.log(parseInt(str.charAt(0)) != NaN))

It says true for some reason. Same with 1M.
As long as I know, NaN is a number type.
Though, I need (parseInt(str.charAt(0)) != NaN) == false in this case. And true in case of 1M.
Thanks for every answer.

PS* parseInt(str) returns NaN

Alireza Ahmadi
  • 7,635
  • 4
  • 11
  • 32

5 Answers5

1

NaN === NaN is false, so you can't just compare them with === or !==

You can use isNaN(parseInt(str.charAt(0)) instead.

Christhofer Natalius
  • 2,219
  • 2
  • 26
  • 34
1

Rather than trying to prove a negative and prove that something is not NaN (remembering that NaN istelf means Not a Number) and expecting a false... too many double negtives

try simply isNaN(str[0])

let str1 = "M1";
let str2 = "1M";

let result1 = isNaN(str1[0]);
let result2 = isNaN(str2[0]);

console.log(result1); // gives true - ie: str1[0] is not a number
console.log(result2); // gives false -ie: str2[0] a number
gavgrif
  • 14,151
  • 2
  • 21
  • 24
1

You can't compare NaN with == operator. Easily check it in if:

let str = "M1"

if(!parseInt(str.charAt(0)))
    console.log("NaN")
Alireza Ahmadi
  • 7,635
  • 4
  • 11
  • 32
1

It is working as expected. NaN is global property and is of not type number.

Here parseInt('M1'.charAt(0)) != NaN will be tested as NaN !== NaN. Since NaN is a global object these two NaN are not pointing same object but two different objects. So it is returning true

In second case (parseInt('1M'.charAt(0)) !== NaN), it is obvious true as 1 !== NaN.

Note: Use === instead of ==

brk
  • 46,805
  • 5
  • 49
  • 71
1

Because: NaN is not equal to NaN

let str = "M1"
console.log(parseInt(str.charAt(0)) != NaN))

parseInt(str.charAt(0)) is a NaN value which is not equal to another NaN value.
Check this out NaN - JavaScript | MDN

Masood Alam
  • 323
  • 5
  • 12