DEV Community

Meditator Gu
Meditator Gu

Posted on

Null>=0 And Undefined>=0 Have Opposite Result Values

Recently, I unified the use of null and undefined in the project according to a technical specification of the company. The variables in some scenarios, whose initial values ​​were undefined, are now changed to null.

After the modification, I found a strange bug that I couldn't find no matter how hard I tried. The logic of the code from top to bottom was normal, but at the end it threw an exception that shouldn't have been thrown.

So I cloned the code again and restored it to the state before the modification. Then I ran the code before and after the modification at the same time. I found that when the code came to an if branch, one of them entered the if branch and the other jumped over it. The if branch looked like this:

const count = pageKidsCountCache.get(currentNode);
// Skip nodes where the page can't be.
if (count >= 0 && currentPageIndex + count <= pageIndex) {
  currentPageIndex += count;
  continue;
}
Enter fullscreen mode Exit fullscreen mode

The value count retrieved from the Map is sometimes empty, that is, undefined. In this case, I changed it to null. Then something went wrong. When the count value was undefined, count>=0 was false. But after changing it to null, it became true. This caused a strange problem.

I entered it twice in the Chrome console and found that JavaScript is indeed like this.
The result value of null>=0 is true, while the result value of undefined>=0 is false.

To further alleviate my confusion, I consulted some documents. The data shows that:
When using relational operators, JavaScript converts non-numeric operands to numbers. By default, null is converted to 0, and undefined is converted to NaN. Because 0>=0, null>=0 is true, and NaN is false when compared to any number, so the value of undefined>=0 is false.

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay