2

I have a function which need to accept both a number and an event. In case of event I will extract that number from target element's attribute. Something like this...

function f(num) {
    if(parseInt(num) == NaN) {
        num = num.target.num
    }
    // Do something with num
}

The result of parseInt(event) is NaN. But strangely the result of parseInt(event) == NaN or parseInt(event)===NaN is false.

Can someone explain what's going on here?

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>


<button onclick="f()">Click me</button>
<p>parseInt(event): <span id="a"></span></p>
<p>parseInt(event)==NaN: <span id="b"></span></p>

<script>
function f(event){
  document.getElementById("a").innerHTML = parseInt(event)
  document.getElementById("b").innerHTML = (parseInt(event)==NaN)
}
</script>
</body>

</html>
Ankur Parihar
  • 458
  • 6
  • 16
  • 1
    don't test for `NaN` with `==`, use `isNaN()` instead ([link to doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN)) – Pac0 May 25 '20 at 13:31

1 Answers1

3

NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN.

For detailed explanation, visit the following:-

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39