Search code examples
javascriptparseint

Strange behaviour of parseInt on event


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>


Solution

  • 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