Null vs Undefined vs Nil: What the Difference Means
Null, undefined, nil, None and NaN all represent absence, but they differ. Learn the distinctions and how to handle missing values safely.
By Velloreth
The problem of absence
Every language needs a way to represent “no value”. The question is how many ways, and what each means.
JavaScript has two: undefined and null. Most other languages have one. The distinction is a frequent source of confusion, and understanding it prevents a class of bugs.
Undefined
undefined means a value has not been assigned. It is the default state.
let x;
x; // undefined
const obj = { a: 1 };
obj.b; // undefined — property does not exist
function f(a) { return a; }
f(); // undefined — argument not passed
[1, 2, 3][10]; // undefined — index out of range
undefined is what you get when you ask for something that is not there. You rarely assign it deliberately.
Its type is "undefined":
typeof undefined; // 'undefined'
Null
null is an explicit assignment meaning “no value”. It is a choice, not a default.
let selectedUser = null; // deliberately empty
Its type is "object", which is a historical bug in JavaScript that cannot be fixed without breaking the web:
typeof null; // 'object' — famously wrong
The practical difference: undefined is what the language gives you, null is what you give the language.
How they differ in practice
Default parameters
function greet(name = 'world') {
return `Hello, ${name}`;
}
greet(undefined); // 'Hello, world' — default applies
greet(null); // 'Hello, null' — default does not apply
Default parameters trigger on undefined only. Passing null explicitly overrides the default.
JSON
JSON.stringify({ a: undefined, b: null });
// '{"b":null}' — undefined is dropped, null is kept
undefined properties vanish in JSON. null survives. This matters when sending data to an API.
Equality
null == undefined; // true — loose equality
null === undefined; // false — strict equality
Loose equality treats them as equal. Strict equality does not. Always use ===.
Arithmetic
null + 1; // 1 — null coerces to 0
undefined + 1; // NaN — undefined coerces to NaN
Absence in other languages
| Language | Value | Notes |
|---|---|---|
| JavaScript | null, undefined | Two values |
| Python | None | One value, singleton |
| Go | nil | Zero value for reference types |
| Ruby | nil | One value, everything is an object |
| Java | null | One value, any reference type |
| C# | null | One value, nullable types |
| Rust | Option<T> | No null; explicit in the type |
| Swift | nil | Optional types |
| Kotlin | null | Nullable types with ? |
| C | NULL | A macro for a null pointer |
Python’s None is a singleton, so identity comparison works:
x = None
x is None # True — the idiomatic check
x == None # works, but `is` is preferred
Go’s nil is the zero value for pointers, slices, maps, channels, interfaces, and functions. A nil map read is fine; a nil map write panics:
var m map[string]int
_ = m["key"] // fine, returns zero value
m["key"] = 1 // panic: assignment to entry in nil map
Rust has no null at all. Absence is represented by Option<T>, which is either Some(value) or None, and the compiler forces you to handle both:
let x: Option<i32> = None;
match x {
Some(v) => println!("{}", v),
None => println!("nothing"),
}
This is the most rigorous approach, and it eliminates null-pointer errors entirely.
NaN is not an absence value
NaN is often confused with null, but it is a numeric value meaning “not a number” — the result of an invalid numeric operation.
0 / 0; // NaN
parseInt('abc'); // NaN
Math.sqrt(-1); // NaN
Number('hello'); // NaN
Its defining oddity is that it is not equal to itself:
NaN === NaN; // false
This is specified by IEEE 754, the floating-point standard. The reasoning is that NaN represents an unknown result, and two unknowns are not necessarily the same.
To test for it:
Number.isNaN(NaN); // true — correct
isNaN('hello'); // true — but coerces first, misleading
Number.isNaN('hello'); // false — no coercion, correct
Always use Number.isNaN, not the global isNaN, which coerces its argument and gives surprising answers.
Safe access patterns
Optional chaining
const city = user?.address?.city;
// undefined instead of a TypeError if any link is missing
Without it:
const city = user && user.address && user.address.city;
Optional chaining also works with method calls and array access:
user?.getName?.();
items?.[0];
Nullish coalescing
const name = input ?? 'anonymous';
?? returns the right side only when the left is null or undefined. This differs from ||, which also triggers on 0, '', and false:
0 || 'default'; // 'default' — probably not what you want
0 ?? 'default'; // 0 — correct
'' || 'default'; // 'default'
'' ?? 'default'; // '' — correct
This distinction causes real bugs. A count of zero or an empty string is a valid value, and || discards it.
Nullish assignment
config.timeout ??= 5000; // assign only if null or undefined
Destructuring defaults
const { name = 'anonymous', age = 0 } = user ?? {};
The ?? {} guard is needed because destructuring null or undefined throws.
Designing away absence
The most robust approach is to avoid absence where possible.
Return empty collections instead of null.
// Fragile
function getPosts(user) {
return user.posts ?? null; // caller must check
}
// Robust
function getPosts(user) {
return user.posts ?? []; // caller can always iterate
}
An empty array is iterable, has a length of zero, and needs no guard. The caller’s code is simpler and cannot crash.
Use a null object.
const guestUser = {
name: 'Guest',
isLoggedIn: false,
permissions: [],
};
Instead of returning null for a missing user, return a guest object with sensible defaults. The caller never needs to check.
Use result types for expected absence.
function findUser(id) {
const user = users.get(id);
return user ? { found: true, user } : { found: false };
}
The absence is explicit in the return shape, so the caller cannot forget it.
Validate at the boundary. Convert nullable inputs into non-nullable internal values once, at the edge of your system, then trust them inside.
Common mistakes
Using || for defaults. It discards valid falsy values. Use ??.
Checking if (x) when you mean if (x != null). An empty string, zero, and false are all falsy but valid.
Comparing with ==. null == undefined is true, which hides the distinction. Use ===.
Assuming typeof null === 'object' is useful. It is a bug. Check x === null instead.
Forgetting that JSON.stringify drops undefined. Data sent to an API may be missing fields you expected.
Mutating a nil map in Go. Reading is fine; writing panics.
Using isNaN instead of Number.isNaN. The global version coerces, producing wrong answers for non-numeric input.
Practical guidance
- Pick one absence value and be consistent across the codebase.
- Use
??not||for defaults. - Use
?.for optional traversal instead of&&chains. - Return empty collections rather than null where the caller iterates.
- Use
Number.isNaNfor numeric checks. - Prefer
===always. - Consider a null object when a sensible default exists.
- Validate at the boundary and keep internals non-nullable.
For the error-handling context, see exceptions vs error codes and error handling patterns that actually work. For the type-system angle, json vs yaml vs toml and form validation patterns.
Quotable summary
undefined means a value was never assigned and is the language’s default; null is an explicit assignment meaning “no value”. Most languages have a single absence value — None in Python, nil in Go and Ruby, null in Java and C# — while JavaScript has two, and they differ in default parameters, JSON serialisation, and equality. NaN is not an absence value but a numeric result meaning “not a number”, and it is unequal to itself by the IEEE 754 specification, so test it with Number.isNaN. Optional chaining and nullish coalescing make missing values safe to traverse, and ?? is correct where || would discard valid falsy values. The most robust design avoids absence entirely, using empty collections, null objects, or explicit result types.