Skip to the page

Arrays, collections and copying · mid

JSON.stringify and JSON.parse in depth

JSON.stringify converts values by fixed rules — it calls toJSON, drops undefined, functions and symbols in objects (but writes null in arrays), turns NaN and Infinity into null, and throws on BigInt and cycles — and those rules are exactly what a JSON.stringify polyfill must reproduce.

The notes

What you must know

  • JSON.stringify(undefined) and JSON.stringify(() => {}) return undefined, not a string.
  • Objects: only own enumerable string keys; properties whose value is undefined, a function or a symbol are left out. Arrays: those values become null.
  • NaN, Infinity and -Infinity become null. Dates become ISO strings through Date.prototype.toJSON. Map and Set become {}.
  • If a value has toJSON(key), its result is used. A replacer function (key, value) or an array of allowed keys filters output. The third argument adds indentation (a number up to 10 or a string).
  • Throws TypeError on circular references and on BigInt.
  • JSON.parse(text, reviver): the reviver runs bottom-up; returning undefined deletes the key; use it to revive dates. In ES2026 the reviver also receives the raw source text (context.source), which helps with big numbers.

The red pen

Common traps: mistake → fix

  • Mistake: undefined becomes null everywhere

    Fix: only inside arrays; in objects the key disappears.

  • Mistake: JSON.stringify(new Map([[1, 2]])) shows the entries

    Fix: it gives '{}'.

  • Mistake: Dates survive a JSON round trip

    Fix: they come back as strings unless a reviver converts them.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does JSON.stringify do with undefined, functions, NaN and Dates?
  2. What are the replacer and space arguments? What is toJSON?
  3. Why does JSON.stringify throw on cycles and BigInt?
  4. Implement JSON.stringify for the common cases. In what order do you check types?
  5. How do you safely send and parse 64-bit IDs?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview