Sign in
Log inSign up
Chris Bongers

76 likes

·

614 reads

6 comments

Jarrod Connolly
Jarrod Connolly
Nov 3, 2020

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.

6
·
·1 reply
Chris Bongers
Chris Bongers
Author
·Nov 3, 2020

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.

·
Francesco Strazzante
Francesco Strazzante
Nov 3, 2020

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.

2
·
·1 reply
Chris Bongers
Chris Bongers
Author
·Nov 3, 2020

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.

·
Shamaayil Ahmed
Shamaayil Ahmed
Nov 3, 2020

Gonna take care.

1
·
·1 reply
Chris Bongers
Chris Bongers
Author
·Nov 3, 2020

Awesome Shamaayil, Thanks for taking the time to comment on my article, appreciate it 🤟

·