S

Sajiron

7 min readPublished on Apr 14, 2025

The Difference Between null, undefined, and NaN in JavaScript

ChatGPT Image Apr 15, 2025, 08_01_48 AM.png

1. Introduction

JavaScript often surprises developers with its type system. Three values that frequently trip up beginners and even seasoned developers are: null, undefined, and NaN.

All three indicate “something went wrong” or “a value is missing”, but they do so in different contexts — and mishandling them can result in hard-to-debug issues.

In this article, you’ll learn:

What each value actually represents

Where you’re most likely to encounter them

How to test for them correctly

And practical patterns for avoiding unexpected bugs

Let’s break them down, one by one.

2. What is undefined?

undefined in JavaScript is a primitive value that signals the absence of a defined value. It is automatically assigned by the JavaScript engine in several situations.

2.1 When Do You Get undefined?

You’ll encounter undefined in these common cases:

a) Declared but not assigned:

let count;
console.log(count); // undefined

b) Accessing non-existent properties:

const user = { name: "Sara" };
console.log(user.age); // undefined

c) Missing function parameters:

function greet(name) {
console.log(`Hello, ${name}`);
}
greet(); // Hello, undefined

d) Implicit returns:

function doNothing() {}
console.log(doNothing()); // undefined

2.2 What You Should Know

JavaScript functions return undefined by default unless told otherwise.

undefined is often used by the JS runtime — you typically shouldn’t assign it yourself.

It is falsy, meaning it behaves like false in conditional logic.

2.3 Type Check

typeof undefined; // "undefined"

This is the only JavaScript value that returns "undefined" from typeof.

3. What is null?

null is also a primitive type, but it represents an intentional absence of any value.

Whereas undefined is often accidental or implicit, null is explicit. You, as the developer, set it.

3.1 Common Use Cases for null

a) Resetting a variable:

let data = fetchData();
data = null; // clear out

b) Representing empty values:

const user = {
name: "Sara",
profile: null, // no profile yet
};

c) Used with optional chaining:

if (user.profile?.bio === null) {
console.log("No bio yet.");
}

3.2 What You Should Know

It’s great for explicitly saying "this has no value yet."

In many APIs and databases, null is used as a placeholder for "not available."

3.3 Type Check (Quirky!)

typeof null; // "object"

This is a well-known bug in JavaScript that’s been around since the beginning. Don’t be fooled — null is not an object.

4. What is NaN?

NaN stands for “Not-a-Number”, but paradoxically, it is actually of type number.

It is a special value that arises only from numeric operations that fail to produce a valid number.

4.1 Common Causes of NaN

a) Invalid math operations:

const result = 0 / 0; // NaN

b) Coercion failures:

parseInt("abc"); // NaN
Math.sqrt(-1); // NaN

c) Operation on undefined:

let x;
console.log(x * 10); // NaN

4.2 Important Notes

NaN is falsy but not equal to itself.

You can’t use === to check for it directly.

4.3 How to Properly Check for NaN

console.log(NaN === NaN); // false ❌
console.log(Number.isNaN(NaN)); // true ✅

Avoid using isNaN() globally — it coerces its argument. Prefer Number.isNaN() for accuracy.

5. Comparing All Three

Here’s a breakdown:

Feature

undefined

null

NaN

Meaning

Not yet assigned

Assigned intentionally as empty

Invalid number

Commonly caused by

Runtime (JS engine)

Developer choice

Bad math or coercion

Type

"undefined"

"object" (quirk)

"number"

Equality (==)

null == undefined → ✅

null == undefined → ✅

NaN == NaN → ❌

Strict equality (===)

false with each other

false

false

Falsy?

✅ Yes

✅ Yes

✅ Yes

6. Common Pitfalls and Gotchas

a) Accidentally treating undefined as null

const data = {}; 
if (data.value === null) {
console.log("It's null!");
}
// Won’t log if it's actually `undefined`

Use == null if you want to catch both:

if (data.value == null) {
console.log("It's null or undefined!");
}

b) Using NaN in calculations silently breaks things

let total = 100 + parseFloat("abc"); // NaN

Use Number.isNaN() to guard against this.

c) Accidentally assigning undefined

obj.value = undefined; // Better: delete obj.value; or use null

7. Best Practices

✅ Use null when resetting values or signaling empty placeholders.

❌ Avoid assigning undefined directly — let JavaScript do it.

✅ Always use Number.isNaN() over == NaN or global isNaN().

🧪 Use optional chaining (?.) and nullish coalescing (??) for safe access.

const name = user.profile?.name ?? "Guest";

8. Conclusion

JavaScript offers a lot of flexibility, but with that comes quirks.

To recap:

undefined means something is missing by default.

null means something is missing on purpose.

NaN means something is mathematically wrong.

Mastering these subtle differences will help you write defensive, bug-free code and debug tricky issues with confidence.