Why does AI-generated JavaScript still use JSON.stringify instead of structuredClone?
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
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
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
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