Skip to main content
CodeOath
← All posts

JavaScript60 min total · 16 parts

JavaScript Array and Object Methods Cheat Sheet

Part 13 of 16 · ~2 min

JSON.stringify and JSON.parse

Converting back and forth between a JavaScript value and JSON text is something you'll do constantly — sending a candidate to an API, caching one in localStorage — often enough that a few of its sharp corners are worth knowing about ahead of time.

JSON.stringify({ name: "Sam Okafor", score: 68, internalNote: undefined });
// '{"name":"Sam Okafor","score":68}' — undefined values are silently OMITTED, not turned into null

JSON.stringify([68, undefined, 82]);
// '[68,null,82]' — but inside an ARRAY, undefined becomes null instead of vanishing

JSON.stringify({ appliedOn: new Date("2026-08-06") });
// '{"appliedOn":"2026-08-06T00:00:00.000Z"}' — a Date is converted to an ISO string automatically

JSON.parse('{"appliedOn":"2026-08-06T00:00:00.000Z"}');
// { appliedOn: "2026-08-06T00:00:00.000Z" } — comes back as a STRING, not a Date — JSON has no date type

Two more arguments to JSON.stringify are easy to forget exist: a second one that filters or reshapes what gets included — either a function, or a plain array naming exactly which keys survive — and a third that controls indentation, for output that's actually meant to be read by a person:

JSON.stringify(candidates[0], ["name", "role"]); // '{"name":"Priya Shah","role":"backend"}'
// useful for a public-facing status page that should never leak `score` or interviewer notes

JSON.stringify(candidates[0], null, 2); // pretty-printed, 2-space indent — handy in a debug log

Send a value through JSON.stringify and back through JSON.parse, and only a fairly narrow set of types make the trip intact: plain objects, arrays, strings, numbers, booleans, null. Everything else pays some price along the way — a Map or Set doesn't come back as one, a Date comes back as a plain string, undefined disappears entirely, and NaN/Infinity both flatten down to null. None of that is a malfunction; it's just outside what the JSON format was ever built to represent — but it means anything richer than plain data needs a custom replacer on the way out and a reviver on the way back in.