DEV Community

Cover image for Why Does NaN === NaN Return False in JavaScript?
Agunechemba Ekene
Agunechemba Ekene

Posted on

2 1 1

Why Does NaN === NaN Return False in JavaScript?

In JavaScript, NaN === NaN evaluates to false, which might seem strange at first. To understand this behavior, we need to explore what NaN represents and why it behaves this way.

What is NaN?
NaN stands for “Not-a-Number” and is used to represent the result of invalid or undefined numerical operations. For example:

console.log(0 / 0);       // NaN
console.log(Math.sqrt(-1)); // NaN

Enter fullscreen mode Exit fullscreen mode

Why Does NaN === NaN Return False?

According to the IEEE 754 floating-point standard, NaN is not equal to anything, including itself. This ensures that invalid results aren’t mistakenly treated as valid. In simple terms, NaN signals an error, and JavaScript treats it as incomparable to anything.

How to Check for NaN
Since direct comparisons won’t work, use these methods to check for NaN:

  • Global isNaN() – checks if a value is NaN or can be converted to it:
console.log(isNaN("abc"));    // true
Enter fullscreen mode Exit fullscreen mode
  • Number.isNaN() – specifically checks for NaN without conversion:
console.log(Number.isNaN(NaN)); // true
Enter fullscreen mode Exit fullscreen mode

Conclusion
NaN === NaN returns false because NaN represents an error, not a valid number. To check for NaN, use isNaN() or Number.isNaN() to avoid confusion and bugs.

Source

💡 One last tip before you go

Spend less on your side projects

We have created a membership program that helps cap your costs so you can build and experiment for less. And we currently have early-bird pricing which makes it an even better value! 🐥

Check out DEV++

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay