Sub topic 4
null and undefined: Two Kinds of Nothing
This chapter assumes you know basic JavaScript syntax, can work with objects and arrays, and can run code in a browser console or Node.js. It also builds on the earlier chapter about the seven primitive types.
JavaScript has two primitive values that mean "no value": undefined and null. They look interchangeable, but the language produces and treats them differently. Knowing which one appears where helps you avoid bugs with defaults, serialization, and comparisons.
The working model
undefinedis what JavaScript itself gives you when a value was never provided. Uninitialized variables, missing properties, missing arguments, and functions with noreturnall produce it.nullis a value that programmers assign on purpose. It means "this slot exists, and it is empty on purpose."
JavaScript sets undefined for you. You write null yourself, and so do APIs such as document.querySelector and String.prototype.match when they find nothing.
Where each one shows up
let pending;
console.log(pending); // undefined: declared, never assigned
const user = { name: "Ada" };
console.log(user.email); // undefined: property does not exist
function greet(name) { return name; }
console.log(greet()); // undefined: argument not passed
function log() {}
console.log(log()); // undefined: no return statement
let selection = null; // deliberately empty
console.log(selection); // nullWhere they behave differently
| Behavior | `undefined` | `null` |
|---|---|---|
| `typeof` result | `"undefined"` | `"object"` (historical quirk) |
| Triggers default parameters | Yes | No |
| Kept by `JSON.stringify` in objects | No, the key is dropped | Yes |
| `Number(value)` | `NaN` | `0` |
| `=== ` each other | `false` | `false` |
| `==` each other | `true` | `true` |
The default-parameter and JSON rows cause the most real bugs:
function setVolume(level = 5) {
return level;
}
console.log(setVolume(undefined)); // 5: default applies
console.log(setVolume(null)); // null: default skipped
console.log(JSON.stringify({ a: undefined, b: null }));
// '{"b":null}': the undefined property disappearsThe numeric conversion difference (NaN versus 0) comes back in the ToNumber chapter and the relational comparison chapter.
Common errors
- Reading a property of either value.
null.lengthandundefined.lengthboth throw aTypeError. Optional chaining, covered later, guards against this. - Assigning
undefinedon purpose. Prefernullwhen you mean "intentionally empty." Then anundefinedin your data always means something was never set. - Checking only one of them. An API value can come back as either one.
value == nullis true for both and for nothing else, so it is one of the few accepted uses of loose equality.
function isMissing(value) {
return value == null; // true only for null and undefined
}
console.log(isMissing(null)); // true
console.log(isMissing(undefined)); // true
console.log(isMissing(0)); // false
console.log(isMissing("")); // falseExercise
A function is declared as function pad(width = 10) { return width; }. What do pad(), pad(undefined), and pad(null) return, and why?
Show answer
pad() and pad(undefined) both return 10, because a default parameter applies only when the argument is undefined. pad(null) returns null, because null counts as a value that was passed on purpose.
Exercise
What does JSON.stringify({ id: 1, note: undefined, tag: null }) produce?
Show answer
'{"id":1,"tag":null}'. JSON has no undefined, so properties with that value are left out, while null is written as a JSON null.