What is the difference between Number.isNaN and globalThis.isNaN

Brandon Evans
2 min readMar 26, 2023
Photo by Viktor Forgacs on Unsplash

In JavaScript, there are two methods for checking whether a value is NaN: Number.isNaN and globalThis.isNaN. While both methods may appear to do the same thing, there are some subtle differences that can cause unexpected behavior in your code if you’re not careful. In this article, we’ll explore the differences between Number.isNaN and globalThis.isNaN and provide some best practices for using them in your code.

Number.isNaN

Number.isNaN is a static method of the Number object that returns true if the provided value is NaN and false otherwise. The key difference between Number.isNaN and the global isNaN function is that Number.isNaN only returns true if the provided value is actually NaN, whereas the global isNaN function attempts to convert the provided value to a number before determining whether it is NaN.

Consider the following examples:

Number.isNaN(NaN); // true
Number.isNaN("hello"); // false
Number.isNaN(undefined); // false
Number.isNaN(42); // false
Number.isNaN("42"); // false

In each of these cases, Number.isNaN behaves as expected: it returns true only for the value NaN.

globalThis.isNaN

First, the global globalThis property contains the global this value, which is usually akin to the global object. And the global isNaN function is a built-in JavaScript function. However, unlike Number.isNaN, the global isNaN function attempts to convert the provided value to a number before determining whether it is NaN. This can lead to unexpected behavior in certain scenarios.

isNaN(NaN); // true
isNaN("hello"); // true
isNaN(undefined); // true
isNaN(42); // false
isNaN("42"); // false

In the above case, I believe you have found the difference, it uses the default type conversion internally, which may not match our expectations.

Best Practices

When checking whether a value is NaN in your code, it is generally recommended to use Number.isNaN instead of the global isNaN function. This is because Number.isNaN only returns true if the provided value is actually NaN, whereas the global isNaN function can return true for values that are not actually NaN.

Conclusion

I hope that this article has helped you better understand the differences between Number.isNaN and globalThis.isNaN in JavaScript. When working with numbers and NaN values in your code, it’s important to understand the nuances of these methods to avoid unexpected behavior.

Thanks for reading! If you’re not yet a Medium member, consider becoming one to support me here, which gives you unlimited access to everything on Medium.

--

--