How to check whether a NaN is a NaN or not in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

NaN is the only value that is not equal to itself. If we check other values, they are equal to themselves but the value NaN is not equal to itself.

Example-1

Live Demo

<html>
<body>
   <script>
      var val = 54/"the";
      document.write(val);
      document.write("</br>");
      if(val == NaN) {
         document.write("NaN is equal to NaN");
      }
      else {
         document.write("check in another way");
      }
   </script>
</body>
</html>

Output

NaN
check in another way

There are some cases, in which we have to use particular conditions. In those conditions, there might be a condition regarding NaN i.e whether a NaN is a NaN or not. So, there is a necessity to build a condition regarding NaN. To get that condition, ES6 has come into the picture. It has provided Object.is() to check whether a NaN is a NaN or not. 

Example-2

Live Demo

<html>
<body>
<script>
   var val = 54/"the";
   document.write(val);
   document.write("</br>");
   document.write(Object.is(val,NaN));
</script>
</body>
</html>

Output

NaN
true
raja
Published on 16-Jul-2019 12:50:27
Advertisements