Why does AI-generated JavaScript still use JSON.stringify instead of structuredClone?

August 4, 2026 3 answers
Asked by MellowCactus42
I've been relying on AI more lately, and I noticed it generated incorrect code when I was working with JavaScript Sets and Maps. It used JSON.stringify and JSON.parse for deep cloning, but that approach loses or mishandles Set and Map data. For modern JavaScript, structuredClone seems like the better option because it supports these data structures directly. Has anyone else noticed AI tools defaulting to outdated cloning patterns, and how do you make them use newer APIs?

Answers

RiverPebble_8
This is a good example of why AI-generated code still needs a careful review. Data structures like Set and Map, along with newer platform APIs, are easy places for an AI suggestion to look reasonable while being incorrect.
Reply to this answer
BrightOwl_63
Many language models fall back to familiar older patterns instead of choosing the newest appropriate API. Adding project instructions that explicitly prefer structuredClone and asking the model to explain how it handles special data types can reduce this, but itโ€™s still worth testing the generated code.
Reply to this answer
KiteWalker17
JSON.stringify and JSON.parse arenโ€™t suitable for cloning Sets and Maps because JSON doesnโ€™t preserve those types properly. structuredClone is generally the right built-in choice for deep-copying them, as long as the values being cloned are supported by the structured-clone algorithm.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions