4 ms·
> Can anyone describe a compelling use case for "deep cloning" objects in JavaScript Sure. A library accepts an object as function argument (for example ‘param
by sesm 3y ago
> Can anyone describe a compelling use case for "deep cloning" objects in JavaScript
Sure. A library accepts an object as function argument (for example ‘params’) and then uses it inside. Modifying users object in-place would be a bad idea.
- WendyTheWillow 3y agoThe smell here is in the library, is the commenter's point. The solution would be to search for a better written library.
- _a_a_a_ 3y agoSure! Use a library that deep-clones the object first, leaving the original parameter unchanged! And now it's slower than the original library you're criticising.
- WendyTheWillow 3y agoOr use a library that doesn’t modify the input…
- _a_a_a_ 3y agoBy deep-copying it, right? Sometimes it is needed.
- WendyTheWillow 3y ago…the whole thread you’re replying to is about it not actually being necessary. To participate in this conversation you either accept that premise or disagree with it, passing it as a given is not really an option for the argument.
- jcparkyn 3y agoIf you know what modifications you need to make (hopefully the library author does), you only need to clone the relevant parts of the object (e.g. with spreading). Deep cloning still isn't usually necessary unless you're doing wierd stuff.
- LegionMammal978 3y agoAnother issue is the opposite situation, where the library reads from the object multiple times, expecting the value to be stable, but the caller might change the value in between, either from the properties using getters or from the library being async. The library has to make a full deep copy to ensure that it's completely stable regardless of the caller's actions. Just freezing the input object would be confusing to the caller and still vulnerable to property getters.
- WendyTheWillow 3y agoThat’s even worse! I would try to avoid a library with a function that fragile.
- slmjkdbtl 3y agoAnother one is exporting an internally used object from the library, you don't want user to be able to modify it.