Why is isNaN(null) == false in JS?



The isNaN() function in JavaScript is used to check whether a given value is NaN. This function converts the argument to a number first, then checks if it's NaN. When you pass null to isNaN(), it returns false, which can be surprising. This happens because of JavaScript type coercion when using isNaN(). In this article, we will understand why isNaN returns false for null.

Understanding isNaN and Type Coercion in Js

Before moving forward in this article you need to understand the following key concepts of this article:

  • isNaN in Js: The isNaN() function is used to check whether a given value is NaN. This function converts the argument to a number first, then checks if it's NaN.
  • Type Coercion in Js: Type coercion in JavaScript is the process of converting values automatically or implicitly from one data type to another in JavaScript.

How isNaN() Works?

The global isNaN() function follows a two-step process:

  • It first converts the argument into a number using the Number() function.
  • Then it checks if the resulting value is NaN. And return the boolean values for the check.

Why Does isNaN(null) Return false?

When you pass null to, isNaN() JavaScript performs type coercion and converts it to a number before checking if it's NaN. Here are the steps:

  • null is converted to a number using Number(null), which results in 0.
  • Since 0 is a valid number and not NaN, isNaN(0) returns false.

Examples

Let's see a practical example of JavaScript isNaN(null) and Type coercion.

// Example of converting null to a number
console.log(Number(null));

// Example of checking if null is NaN
console.log(isNaN(null));

Output

0
false

Let's see example with different value such as undefined.

// Example of converting undefined to a number
console.log(Number(undefined));

// Example of checking if undefined is NaN
console.log(isNaN(undefined));

Output

NaN
true

Let's see one more example for cross checking the value of isNaN(null) using Number.isNaN(). This method doesn't convert the value first and strictly checks whether a value is exactly NaN.

// Example of checking if null is NaN
console.log(Number.isNaN(null));

Output

false

Conclusion

In this article, we have understood why isNaN(null) returns false in JavaScript. The reason is that null is changed to 0 when it's converted to a number and 0 is not NaN. Knowing about this type coercion is important for working with numbers in JavaScript.

Updated on: 2025-03-17T12:33:08+05:30

695 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements