🤯 undefined, null, and NaN in JavaScript – Explained Clearly

pushpesh kumarpushpesh kumar
3 min read

If you're new to JavaScript (or even experienced), undefined, null, and NaN can feel like three very confusing cousins.
They all seem to mean "nothing" — but they're very different kinds of nothing.

Let’s clear it all up, once and for all.


1️⃣ undefinedThe default “nothing”

🔍 What is it?

undefined means: “This variable exists, but it hasn’t been assigned a value yet.”

✅ You get undefined when:

let a;
console.log(a); // undefined (no value assigned)
function greet(name) {
  console.log(name);
}
greet(); // undefined (no argument passed)
const obj = {};
console.log(obj.age); // undefined (property doesn’t exist)

❗ Important Notes:

  • undefined is the default return value of functions that don’t return anything.

  • Don’t manually assign undefined yourself. Use null instead when you intentionally mean “nothing”.


2️⃣ nullIntentional emptiness

🔍 What is it?

null is explicit nothing. It’s used to show “we have nothing here on purpose.”

✅ Example:

let userProfile = null; // User hasn’t logged in yet
const response = {
  error: null,
  data: []
};

❗ Important Notes:

  • typeof null return object while typeof undefined return undefined

  • Use null to reset a variable, empty a field, or indicate an intentional absence.


3️⃣ NaNNot a Number (but still a number)

🔍 What is it?

NaN is a special value that means: “This is not a valid number, even though we expected one.”

✅ Example:

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

❗ Important Notes:

  • typeof NaN === "number" ← Weird but true.

🔍 Side-by-Side Comparison

FeatureundefinednullNaN
MeansVariable exists, but no valueIntentionally emptyInvalid number
Typeundefinedobject (quirk)number
Use-caseUnassigned variables, missing paramsManual reset or empty slotBad math or invalid number conversion

✅ When to Use What?

SituationUse
You haven’t assigned a value yetLet it be undefined (automatic)
You want to intentionally empty a variable or objectUse null
You’re doing math and the result is invalidJavaScript will give you NaN

🧪 Quiz Yourself!

What will this log?

let a;
let b = null;
let c = "hello" * 3;

console.log(a);  // ?
console.log(b);  // ?
console.log(c);  // ?
undefined
null
NaN

🎯 Final Tip

  • Use null intentionally

  • Don’t assign undefined manually

  • Always check for NaN using Number.isNaN()

0
Subscribe to my newsletter

Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

pushpesh kumar
pushpesh kumar