76 likes
·
614 reads
6 comments
A great introduction to shallow vs deep cloning in JavaScript.
Be careful using JSON parse/stringify to deep clone as it does not support some JavaScript features when used to clone objects. Date objects will convert to strings. Functions, symbols, and undefined are also not correctly converted over.
Just a couple of things to watch out for if one is looking for a proper deep clone. Better off to use something like lodash cloneDeep for correctness and performance reasons.
Hey Jarrod,
Yes as mentioned in the article for robust deep-cloning one should use lodash deepclone or any other library.
For simple "flat" objects this JSON method works really well.
It does not work for Data objects for instance, they will forget that they are actual date objects.
Great and useful post! Thank you Chris. 😎 Years ago I remember I used cloneDeep: the function from lodash, but it tooks a while to understand the problem. This pointer creation when use "=" it's not widely known unfortunately.
Hey Francesco, Haven't used the deepClone often myself, what exactly happens when you use the =? I mainly choose the JSON method or make my own deepClone specific for typecasting.
Gonna take care.
Awesome Shamaayil, Thanks for taking the time to comment on my article, appreciate it 🤟