Hacker News new | ask | show | jobs
by Karnickel 3068 days ago
In most common cases, like shallow clones and cloning simple objects, are already well-covered and solved, often with very few lines of code or even just a single command (`Object.assign()`). Stage 4 draft (i.e. it will be in the next version): `{ ...obj }` to clone an object [0].

Cloning Arrays, Maps, Sets is easy using their default constructors in a single line, such as `new Map(originalMap)` or `new Set(originalSet)` [1]. You can clone an array using spread syntax or `Array.from` [2].

Another issue is that there are many variants of "deep cloning". Some people only need actual "regular" object properties cloned - copying objects without any of the features you get through `Object.defineProperty()`, like object literals.

Some people want symbols cloned, others don't.

Some people don't care about functions. Some people want some things, like functions, not cloned but referenced to avoid duplication.

Some people want all the options copied that you get from `Object.defineProperty()`.

Some people care about the prototype chain, others don't (if you only clone regular objects, e.g. from object literal object creation and similar ones).

So there is huge variety about what people need when they talk about "deep-copying" in Javascript, because objects have so many optional features, but most of the time they are not needed or not relevant to the copying.

As others have said, it also is not actually all that essential. I use a functional style without OOP (this, bind, class (ES6 or ES5 "pseudo-class" construction), try not to mutate, and I rarely need deep-cloning, if at all. I think right now I only use my carefully crafted and speed-tested deep-clone module in tests. Each time I started using it in my code I eventually came up with a much better solution that didn't need it. Note that I did not actively try to avoid it, it just happened - the use case went away by itself each time I came up with an improved version of the code.

[0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

[1] https://stackoverflow.com/a/30626071/544779

[2] https://www.briangonzalez.org/post/copying-array-javascript