Sub topic 4
What Happens to undefined, Functions, Symbols, NaN, and Dates
JSON has six kinds of values: objects, arrays, strings, numbers, booleans, and null. JavaScript has many more. When you pass a value to JSON.stringify that JSON cannot represent, the method does not throw in most cases. It applies a fixed set of rules: it drops the value, replaces it with null, or converts it to something JSON can hold. These rules are predictable once you know them. If you don't, they cause bugs that are hard to spot, such as a field that vanishes from an API payload or a date that comes back as a plain string.
This chapter assumes you already know the basic use of JSON.stringify and JSON.parse from the earlier chapters, and that you are comfortable with JavaScript primitives, objects, arrays, and the Date type.
The Core Rule: Context Decides the Outcome
The same value can be handled three different ways depending on where it appears:
- As an object property value, an unsupported value causes the whole property to be omitted.
- As an array element, it becomes
null, so the array keeps its length and its indexes. - As the top-level value passed to
stringify, it makes the method returnundefined(the JavaScript value, not a string).
Arrays get null because removing an element would shift every later index. Object properties can be dropped because no other key depends on their position.
const data = {
a: undefined,
b: () => 1,
c: Symbol("s"),
d: NaN,
e: new Date(0)
};
console.log(JSON.stringify(data));
// {"d":null,"e":"1970-01-01T00:00:00.000Z"}
console.log(JSON.stringify([undefined, () => 1, Symbol("s")]));
// [null,null,null]
console.log(JSON.stringify(undefined)); // undefined (not a string)In the object, a, b, and c disappear entirely. In the array, the same three values each turn into null. At the top level, nothing is produced at all.
undefined: Missing Versus Null
JSON has no undefined. The practical consequence is that a property set to undefined and a property that does not exist produce the same output:
console.log(JSON.stringify({ name: "Ada", nickname: undefined })); // {"name":"Ada"}
console.log(JSON.stringify({ name: "Ada" })); // {"name":"Ada"}
console.log(JSON.stringify({ name: "Ada", nickname: null })); // {"name":"Ada","nickname":null}This matters for APIs that treat "field absent" and "field is null" differently. A common example is a PATCH endpoint, where an absent field means "leave unchanged" and null means "clear this value". If your code builds the request body with nickname: undefined to mean "clear it", the server never sees the field and leaves the old nickname in place. Use null when you want the receiver to know about the field.
Functions and Symbols
Functions are behavior, not data, so JSON has nowhere to put them. Methods on an object are dropped just like any other function-valued property:
const counter = {
count: 3,
increment() { this.count++; }
};
console.log(JSON.stringify(counter)); // {"count":3}That is usually what you want. It does mean that after a round trip through JSON, the object has its data but none of its methods. Restoring behavior requires rebuilding instances, which the reviver chapter covers.
Symbols are dropped in two places. Symbol values follow the omit, null, or undefined rule above. Symbol keys are ignored completely, whatever value they hold:
const secret = Symbol("secret");
const obj = { visible: 1, [secret]: "hidden" };
console.log(JSON.stringify(obj)); // {"visible":1}JSON.stringify only looks at an object's own enumerable string-keyed properties. Symbol-keyed properties, non-enumerable properties, and inherited properties are all skipped.
NaN, Infinity, and Negative Zero
JSON numbers must be finite. NaN, Infinity, and -Infinity are written as null in every context, including object properties. They are never omitted:
console.log(JSON.stringify({ ratio: 0 / 0, max: 1 / 0, min: -1 / 0 }));
// {"ratio":null,"max":null,"min":null}
console.log(JSON.stringify([NaN, Infinity])); // [null,null]
console.log(JSON.stringify(NaN)); // "null"
console.log(JSON.stringify(-0)); // "0"Note the difference from undefined: JSON.stringify(NaN) returns the string "null", while JSON.stringify(undefined) returns no string at all.
The conversion is one-way. After a round trip, NaN comes back as null, and null behaves differently in arithmetic: null + 1 is 1, while NaN + 1 is NaN. A failed calculation that produced NaN can turn into a quiet zero-like value on the other side. If a computed number may be non-finite, check it with Number.isFinite before serializing and decide on purpose what to send.
Negative zero becomes 0. This rarely matters, but it does mean Object.is(JSON.parse(JSON.stringify(-0)), -0) is false.
Dates Become ISO Strings
Dates are the one common type that serializes to something useful by default. Date.prototype has a built-in toJSON method that returns the same string as toISOString(): a UTC timestamp in ISO 8601 format. JSON.stringify calls toJSON before deciding how to serialize a value, so the Date is replaced by that string.
const event = { name: "launch", at: new Date(Date.UTC(2024, 0, 15, 9, 30)) };
const text = JSON.stringify(event);
console.log(text); // {"name":"launch","at":"2024-01-15T09:30:00.000Z"}
const back = JSON.parse(text);
console.log(typeof back.at); // "string"
console.log(back.at instanceof Date); // falseHere is the asymmetry. stringify turns the Date into a string, and parse has no way to know that string was ever a Date. Calling back.at.getFullYear() throws a TypeError. You must convert it back yourself, either by hand with new Date(back.at) or with a reviver, as a later chapter shows.
Two more details:
- The output is always UTC with a
Zsuffix. The original time zone offset is not preserved, though the instant in time is. - An invalid Date serializes to
null, because itstoJSONreturnsnullwhen the time value is not finite.
console.log(JSON.stringify({ when: new Date("not a date") })); // {"when":null}Other Built-ins That Lose Information
Many built-in types have no enumerable own properties, so they serialize as empty objects. No error is thrown, so these losses go unnoticed:
console.log(JSON.stringify(new Map([["a", 1]]))); // {}
console.log(JSON.stringify(new Set([1, 2]))); // {}
console.log(JSON.stringify(/ab+c/g)); // {}
console.log(JSON.stringify(new Error("boom"))); // {}
console.log(JSON.stringify(new Uint8Array([1, 2]))); // {"0":1,"1":2}
console.log(JSON.stringify(new Number(5))); // 5
console.log(JSON.stringify([1, , 3])); // [1,null,3]An Error comes out empty because message and stack are non-enumerable. This catches people who log errors with JSON.stringify and see {}. Wrapper objects such as new Number(5) and new String("x") are unwrapped to their primitive values. Holes in sparse arrays become null, the same as undefined elements.
The one built-in that throws instead of degrading quietly is BigInt. JSON.stringify({ n: 10n }) raises a TypeError. That case, along with precision loss for large numbers, has its own chapter.
Summary Table
| Value | As object property | As array element | At top level |
|---|---|---|---|
| `undefined` | omitted | `null` | returns `undefined` |
| function | omitted | `null` | returns `undefined` |
| symbol value | omitted | `null` | returns `undefined` |
| symbol key | ignored | not applicable | not applicable |
| `NaN`, `Infinity`, `-Infinity` | `null` | `null` | `"null"` |
| `-0` | `0` | `0` | `"0"` |
| valid `Date` | ISO string | ISO string | ISO string |
| invalid `Date` | `null` | `null` | `"null"` |
| `Map`, `Set`, `RegExp`, `Error` | `{}` | `{}` | `"{}"` |
| `BigInt` | throws `TypeError` | throws `TypeError` | throws `TypeError` |
Common Errors
- Assuming a round trip is lossless.
JSON.parse(JSON.stringify(x))gives back an equal value only ifxcontains nothing but plain objects, arrays, strings, finite numbers, booleans, andnull. - Using
undefinedto mean "clear this field." The field disappears from the output. Sendnullinstead. - Calling Date methods on parsed data. Parsed dates are strings until you convert them.
- Logging errors with
JSON.stringify. You get{}. Copymessageandstackinto a plain object first, or log the error directly. - Forgetting that
stringifycan returnundefined. Check the result before passing it to an API that expects a string.
Exercise
What does this log? console.log(JSON.stringify({ a: [undefined, NaN], b: undefined, c: new Date(NaN), d: new Set([1]) }))
Show answer
{"a":[null,null],"c":null,"d":{}}. Inside the array, undefined and NaN both become null. The property b is omitted because its value is undefined. The invalid Date's toJSON returns null. The Set has no enumerable own properties, so it becomes {}.
Exercise
A client sends JSON.stringify({ id: 4, email: user.email }) to a PATCH endpoint, where an absent field means "unchanged" and null means "remove". When the user clears their email, the code sets user.email = undefined, but the server keeps the old address. Why, and what is the fix?
Show answer
email: undefined is omitted during serialization, so the body is {"id":4} and the server treats the email as unchanged. Set user.email = null (or map undefined to null before serializing) so the body becomes {"id":4,"email":null}.
Exercise
After const copy = JSON.parse(JSON.stringify({ created: new Date(0) })), the call copy.created.getTime() throws. Explain the cause and write one line that fixes copy.created.
Show answer
stringify calls Date.prototype.toJSON, which turns the Date into the string "1970-01-01T00:00:00.000Z", and parse returns that string unchanged, so it has no getTime method. Fix it with copy.created = new Date(copy.created);.