News for hackers. Stuff that matters.
Re:Deep Cloning Objects in JavaScript, the Modern Way by chatmasta on Thursday December 21, 2023 @07:00PM (#38728944)
Unpopular opinion:

I have never needed to "deep clone" an object in JavaScript. Any time I thought I needed to do that, it was actually a code smell for a different underlying problem.

I was glad to see the end of the "immutable everything" dogmatic obsession wrought by Redux. The code smell in that case was usually related to passing entire objects as props.

Can anyone describe a compelling use case for "deep cloning" objects in JavaScript (keep in mind _everything_ is an object in JavaScript) that isn't dancing around some hidden complexity? IMO, if it can't be (de)serialized via JSON.stringify and JSON.parse, then you should consider why you're trying to serialize it in the first place, and why you're scared to pass around the reference to the object. (That said, structuredClone looks like a better alternative to the JSON method - but note it's still not cloning functions, so you should still be careful where/when you use it.)

Re:Deep Cloning Objects in JavaScript, the Modern Way by laurencerowe on Thursday December 21, 2023 @09:01PM (#38730016)
Pedantically, while _everything_ is an object is true for Python it’s not for JavaScript which has distinct primitive types for strings, numbers, booleans, symbols, and undefined.
Re:Deep Cloning Objects in JavaScript, the Modern Way by jholman on Thursday December 21, 2023 @10:22PM (#38730607)
And null. I know that typeof(null) says 'object', but it's lying. When I say "it's lying", I mean that according to the spec, null is of type null. Also it has absolutely nothing in common with objects except for the output of typeof.

Also these days there's BigInt.

Re:Deep Cloning Objects in JavaScript, the Modern Way by baq on Friday December 22, 2023 @03:19AM (#38732132)
JS is amazing.

As in, it’s amazing that anything actually works given the internal inconsistencies in its core.

(Disclaimer: I code ts/js for a living.)

Re:Deep Cloning Objects in JavaScript, the Modern Way by madeofpalk on Thursday December 21, 2023 @07:13PM (#38729065)
The most common reason I've had to do it is to log objects to the console.

Chrome dev tools logs a pointer to the object, so if the object is mutated after logging, but before you view/expand it (especially for nested structures), it can be very confusing! JSON.parse(JSON.stringify()) usually is good enough for this :)

But yes, generally speaking I think a deep clone is a sign of a smell elsewhere. That doesn't mean it never has a place in any code, but just that if I find myself reaching for it, I usually see if there's a mistake being made elsewhere.

Re:Deep Cloning Objects in JavaScript, the Modern Way by dylan604 on Thursday December 21, 2023 @07:19PM (#38729132)
Isn't that desired? You want to see what the object looks at at the time of logging. If you need to see it after some additional code has run, you log it again.
Re:Deep Cloning Objects in JavaScript, the Modern Way by Akronymus on Thursday December 21, 2023 @07:23PM (#38729169)
The problem is that if you log one object multiple times, they all point to the same object.

So if between two logs it was modified, it reflects the new status on the log before as well.

I think you may have been confused and got how it is, vs how it ought to be the wrong way round.

Re:Deep Cloning Objects in JavaScript, the Modern Way by jv22222 on Thursday December 21, 2023 @08:25PM (#38729741)
That's just one of the reasons I always say...

https://twitter.com/justinvincent/status/1714866433426067573

Re:Deep Cloning Objects in JavaScript, the Modern Way by dylan604 on Thursday December 21, 2023 @08:03PM (#38729548)
to be honest, my experience with logging objects is so simple, i've never needed to try this live look into the object. my expectation was the log is a snap shot in time, not a live look at the object. an interactive view into the object does sound interesting rather than constant log entries for each step. which is how I would have tried to do something the first time only to be confused by it. TIL.
Re:Deep Cloning Objects in JavaScript, the Modern Way by jholman on Thursday December 21, 2023 @10:19PM (#38730584)
What the parent posts are trying to hint to you is that the default logging behaviour of the console is the live-look model, which is almost never what you wanted with logging. (Though it does have other uses.) To avoid the live-look, you can deep clone, or just stringify.
Re:Deep Cloning Objects in JavaScript, the Modern Way by jay_kyburz on Thursday December 21, 2023 @08:11PM (#38729619)
Wow, I never knew this.
Re:Deep Cloning Objects in JavaScript, the Modern Way by cortesoft on Thursday December 21, 2023 @10:23PM (#38730614)
You have it opposite… if you change the object after logging, it will retroactively change the logged version.
Re:Deep Cloning Objects in JavaScript, the Modern Way by recursive on Thursday December 21, 2023 @11:49PM (#38731053)
> You want to see what the object looks at at the time of logging

Yes. That's why you need to use structuredClone. If you don't, and you mutate the object, then you'll see the new values when you expand the object.

Re:Deep Cloning Objects in JavaScript, the Modern Way by sesm on Thursday December 21, 2023 @07:18PM (#38729122)
> 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.

Re:Deep Cloning Objects in JavaScript, the Modern Way by WendyTheWillow on Thursday December 21, 2023 @07:40PM (#38729319)
The smell here is in the library, is the commenter's point. The solution would be to search for a better written library.
Re:Deep Cloning Objects in JavaScript, the Modern Way by _a_a_a_ on Thursday December 21, 2023 @07:53PM (#38729450)
Sure! 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.
Re:Deep Cloning Objects in JavaScript, the Modern Way by WendyTheWillow on Thursday December 21, 2023 @08:09PM (#38729600)
Or use a library that doesn’t modify the input…
Re:Deep Cloning Objects in JavaScript, the Modern Way by _a_a_a_ on Thursday December 21, 2023 @08:12PM (#38729625)
By deep-copying it, right? Sometimes it is needed.
Re:Deep Cloning Objects in JavaScript, the Modern Way by WendyTheWillow on Thursday December 21, 2023 @08:47PM (#38729922)
…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.
Re:Deep Cloning Objects in JavaScript, the Modern Way by jcparkyn on Thursday December 21, 2023 @10:25PM (#38730621)
If 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.
Re:Deep Cloning Objects in JavaScript, the Modern Way by qayxc on Friday December 22, 2023 @06:16AM (#38733119)
The Date object would like to have a chat with you ;)
Re:Deep Cloning Objects in JavaScript, the Modern Way by jcparkyn on Thursday December 28, 2023 @06:55PM (#38800229)
I know you were mostly joking, but for cloning dates you can "just" use the constructor (https://stackoverflow.com/a/69601256).
Re:Deep Cloning Objects in JavaScript, the Modern Way by LegionMammal978 on Thursday December 21, 2023 @11:34PM (#38730965)
Another 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.
Re:Deep Cloning Objects in JavaScript, the Modern Way by WendyTheWillow on Friday December 22, 2023 @01:32AM (#38731549)
That’s even worse! I would try to avoid a library with a function that fragile.
Re:Deep Cloning Objects in JavaScript, the Modern Way by slmjkdbtl on Thursday December 21, 2023 @10:54PM (#38730769)
Another one is exporting an internally used object from the library, you don't want user to be able to modify it.
Re:Deep Cloning Objects in JavaScript, the Modern Way by efortis on Thursday December 21, 2023 @08:33PM (#38729796)
Undo. I use it in UI Drafter for handling Undo.

For example, I create a revision of a store (a deep clone) and apply the undo frames one-by-one.

Each undo frame has the setter name and its arguments. IOW, the frames contain what changed, such as:

    [
      [BASE.setCard, 'some-id', CF.title, 'The New Title'],
      …more frames
    ]

Here's a post with more details

https://blog.uidrafter.com/architecture-of-a-desktop-alike-s...

Re:Deep Cloning Objects in JavaScript, the Modern Way by giankam on Friday December 22, 2023 @03:27AM (#38732184)
Yep, I do the same.
Re:Deep Cloning Objects in JavaScript, the Modern Way by endisneigh on Thursday December 21, 2023 @07:08PM (#38729002)
There are plenty of reasons to deepclone. That being said I do share some agreement. JavaScript imo is best when you limit complex structures and stick with primitives, ideally just one layer deep, but there are situations when it can’t be helped, e.g, dealing with api calls.
Re:Deep Cloning Objects in JavaScript, the Modern Way by chatmasta on Thursday December 21, 2023 @07:11PM (#38729047)
Yep. But API calls traverse the network, and assuming that's via JSON, you're already losing functionality like Date parsing, so the litmus test of JSON.stringify/parse seems appropriate to determine if you're dealing with a true "data object." If you run into issues with things like Dates, then it's a smell indicating a potential point of divergence in different codepaths that handle the network call differently.
Re:Deep Cloning Objects in JavaScript, the Modern Way by endisneigh on Thursday December 21, 2023 @07:16PM (#38729084)
I don’t disagree, but just responding to your comments first paragraph.
Re:Deep Cloning Objects in JavaScript, the Modern Way by kevincox on Thursday December 21, 2023 @08:13PM (#38729638)
The saving grace here is that it destroys classes. I have often seen deep clone and deep equals as a sort of back-door API that then breaks when the implementation of the class does. The fact that this ignores prototypes makes it clear that you should only be using this for data, not "OO Objects".
Re:Deep Cloning Objects in JavaScript, the Modern Way by jv22222 on Thursday December 21, 2023 @08:14PM (#38729649)
> Can anyone describe a compelling use case for "deep cloning" objects in JavaScript

Hierarchical data structures, in mindmaps, menu structures, block based notes apps, etc.

Re:Deep Cloning Objects in JavaScript, the Modern Way by niedzielski on Thursday December 21, 2023 @10:45PM (#38730733)
I agree. I had this same problem with a tree UI model. Each node had links to both the children and the parent. Mutating any node in the tree, changes the reference of that node. Mutating the linkage to the updated node cascades to every other node in the tree.
Re:Deep Cloning Objects in JavaScript, the Modern Way by hutzlibu on Thursday December 21, 2023 @08:01PM (#38729537)
One use case I have, which I do not like, but there is literally no other way:

Communicating with workerthreads.

I so much would like to pass references of big readonly objects towards them - but no, full copy it is, for every thread.

Re:Deep Cloning Objects in JavaScript, the Modern Way by chatmasta on Thursday December 21, 2023 @08:24PM (#38729729)
You're probably aware of this, but in some cases you might be able to use SharedArrayBuffer [0], which doesn't make a copy of the underlying data but does use structured cloning to clone the outside of the object.

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

Re:Deep Cloning Objects in JavaScript, the Modern Way by hutzlibu on Thursday December 21, 2023 @08:35PM (#38729814)
I only used it for experimentation so far, but I abondoned it, after I learned, that only one worker can be the active user of a SharedArrayBuffer. So they cannot be shared at the same time? Sharing seems to mean, now A uses it, than gives control back, via the main thread, then B uses it, etc

(but I hope I missunderstood something there)

But I need many threads to access the same data, at the same time (readonly, so no racecondition).

Re:Deep Cloning Objects in JavaScript, the Modern Way by bongobingo1 on Thursday December 21, 2023 @10:26PM (#38730630)
Ah, the OnlyChild implementation of Shared.
Re:Deep Cloning Objects in JavaScript, the Modern Way by kaoD on Friday December 22, 2023 @04:33AM (#38732555)
Are you sure about this?

You might be mixing ArrayBuffer (which is a transferrable object[0] and gets zero-copy moved) and SharedArrayBuffer.

From [1]:

> The structured clone algorithm accepts SharedArrayBuffer objects and typed arrays mapped onto SharedArrayBuffer objects. In both cases, the SharedArrayBuffer object is transmitted to the receiver resulting in a new, private SharedArrayBuffer object in the receiving agent (just as for ArrayBuffer). However, the shared data block referenced by the two SharedArrayBuffer objects is the same data block, and a side effect to the block in one agent will eventually become visible in the other agent.

[0] https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers...

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

Re:Deep Cloning Objects in JavaScript, the Modern Way by hutzlibu on Friday December 22, 2023 @05:59AM (#38733017)
"Are you sure about this?"

No. And I hope to be wrong.

I will give it another try then, but I was using SharedArrayBuffer and I was getting explicit errors about this limitation.

Re:Deep Cloning Objects in JavaScript, the Modern Way by kaoD on Friday December 22, 2023 @07:01AM (#38733341)
Did a quick test and seems to work as expected: https://codesandbox.io/p/devbox/sharedarraybuffer-33qywc (see console in https://33qywc-3000.csb.app/)

Caveat is you need these headers for security reasons (hence why the sandbox above has Express) or SharedArrayBuffer is not even defined (at least in Firefox):

    Cross-Origin-Opener-Policy: same-origin
    Cross-Origin-Embedder-Policy: require-corp
Re:Deep Cloning Objects in JavaScript, the Modern Way by holoduke on Thursday December 21, 2023 @07:05PM (#38728981)
An object containing just data for sure having lots of usecases. Like i.e undo/redo. But deep cloning would be as simple as json.parse(json.stringify(object))
Re:Deep Cloning Objects in JavaScript, the Modern Way by chatmasta on Thursday December 21, 2023 @07:13PM (#38729062)
Yeah, agreed. And in that case you should treat the "data object" as opaque, in which case it should be sufficient to pass it by reference. Hence, if you're reaching for deepClone, it's a code smell - why can't you pass the reference? Are you mutating the data object somewhere that you shouldn't be?
Re:Deep Cloning Objects in JavaScript, the Modern Way by compacct27 on Thursday December 21, 2023 @07:20PM (#38729135)
React needs a new object for its hooks when you change them. We need to modify those objects, so deepClone + direct mutation on the clone bypasses a lot of annoying immutable object creation bs. ppl just destructure the whole thing anyways, which is actually also pretty slow
Re:Deep Cloning Objects in JavaScript, the Modern Way by chatmasta on Thursday December 21, 2023 @08:25PM (#38729743)
React hooks don't need to add the entire object to their dependency array; they can specify only the properties that are actually dependencies of the logic contained in the hook.
Re:Deep Cloning Objects in JavaScript, the Modern Way by jcparkyn on Thursday December 21, 2023 @10:20PM (#38730592)
You should check out immer for that use case ("modifying" an immutable object with imperative code).
Re:Deep Cloning Objects in JavaScript, the Modern Way by davidmurdoch on Thursday December 21, 2023 @07:14PM (#38729070)
In my circles, "immutable everything" was from the functional purists.
Re:Deep Cloning Objects in JavaScript, the Modern Way by Waterluvian on Thursday December 21, 2023 @07:17PM (#38729110)
Immutable structures are beautiful when I’ve got an editor for geographic data and want a high performance undo/redo stack with basically no effort. It’s also considerably cheaper to identify when groups of polygons have changed by object identity rather than deep equality. Did this property change? Did properties in general change? Did this polygon change? Did this collection of polygons change? All using === equality checks without any manual plumbing. About ten years into doing it this way and I’ve got one regret: starting with ImmutableJS instead of Immer.
Re:Deep Cloning Objects in JavaScript, the Modern Way by dtx1 on Thursday December 21, 2023 @07:40PM (#38729316)
I am building a card game engine in typescript. A simple AI based on monte carlo tree search requires me to copy the gamestate a lot. And it's always a list of cards that i'm modeling so I really need to deepclone arrays.
Re:Deep Cloning Objects in JavaScript, the Modern Way by chatmasta on Thursday December 21, 2023 @08:37PM (#38729829)
Can you not serialize this state to/from JSON? I'd encourage trying to reduce the state to be JSON-serializable, and then re-initialize any "classes" after deserializarion with a .fromJSON() method (the "factory method" pattern) - in fact you can even call such .toJSON() "replacer" [0] and .fromJSON() "reviver" [1] functions in a callback passed to JSON.stringify and JSON.parse.

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

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

Re:Deep Cloning Objects in JavaScript, the Modern Way by jholman on Thursday December 21, 2023 @10:27PM (#38730641)
How is this better than deepcopying?

Deserializing requires paying all the same costs as deepcopying, both in terms of compute time and in terms of memory usage, but it also incurs the extra costs of parsing.

I'm not saying that there wouldn't be benefits to having a serializer for their gamestate (because there would surely be benefits), but I just cannot understand this as an alternative for the problem they described.

Re:Deep Cloning Objects in JavaScript, the Modern Way by dtx1 on Thursday December 21, 2023 @08:41PM (#38729863)
I haven't really gotten to the point where anything works but doing the serialize de/serialize combo is possible. The issue is, that I am thinking about doing this not a few hundred times but more like several million times (preferably per minute), so i'll likely have to implement several competing versions and benchmark them.

The full idea is implement a deckbuilding game like magic and use genetic algorithms and montecarlo simulation to balance the card pool. But that requires millions of games with millions of simulations to work. So i'll see if it's even possible.

Re:Deep Cloning Objects in JavaScript, the Modern Way by chatmasta on Thursday December 21, 2023 @08:59PM (#38730004)
If you really need maximum performance then you probably don't want to deal with JS objects at all. (But you should benchmark it first... you might be surprised how far V8 gets you with JIT optimizations - although serialization will be a bottleneck whether you're using JSON or deepClone.) For example, as one potential alternative, you could invent a scheme for encoding the state in a bit array, and then find clever bitwise operations for inspecting or manipulating it.

For inspiration, many chess engines store game state in a "bitboard" [0] which is a 64 bit representation of some (partial) state of the board.

Of course, at this point you might not even want to be using JavaScript... maybe you could write the hot path in Rust, compile it to wasm, and then use JS for orchestration/UI.

[0] https://en.wikipedia.org/wiki/Bitboard#Chess_bitboards

Re:Deep Cloning Objects in JavaScript, the Modern Way by dtx1 on Thursday December 21, 2023 @09:18PM (#38730135)
That is really useful, thank you! I think first stage is building the game and see if the whole Genetic Algorithm/Monte Carlo Setup actually works, even if the first few iterations take weeks.

The issue is I want to figure out if there are combos that I don't even know exist that are unusually strong. Basically make sure I balance the card pool but automatically.

Re:Deep Cloning Objects in JavaScript, the Modern Way by chatmasta on Thursday December 21, 2023 @11:31PM (#38730953)
> first stage is building the game

Yeah :) Definitely better to make it slow but ship it. Then make it fast later.

Re:Deep Cloning Objects in JavaScript, the Modern Way by jholman on Thursday December 21, 2023 @10:32PM (#38730663)
There are at least two obvious alternatives to (fully) deepcloning.

First, many "everything must be immutable" libraries provide data structures that give operations that feel like mutations (but actually are not), and many of those can re-use all the old objects that are not mutated. This could save a lot, relative to full naive deepcopies. Or it could save very little, depending on what you're doing.

Second, if you have the ability, you can always mutate before recursion and then revert when the recursion finishes. This could potentially be very tricky, because it's not always easy to revert mutations. As such, it's not a good plan for a prototype, but if you can get it right, this could make your tree search wayyyyy faster.

Re:Deep Cloning Objects in JavaScript, the Modern Way by quickthrower2 on Thursday December 21, 2023 @10:26PM (#38730627)
If something is immutable then you never need to clone it. Just copy the reference.

If an object is immutable and you want to copy/mutate one item it then you can surgically clone it in O(how deeply nested the item to change is). Object spread being the simple case.

JS makes this messy to do though! Lots of spreads and array maps or you pull in a library like Immer and now have “coloured” objects. Immutability in JS is not idiomatic so for that reason I try to avoid unless I really need to.

Re:Deep Cloning Objects in JavaScript, the Modern Way by ehutch79 on Thursday December 21, 2023 @11:05PM (#38730815)
An edit dialog where you want to be able to cancel editing without leaving changes on the original object.
Re:Deep Cloning Objects in JavaScript, the Modern Way by namuol on Thursday December 21, 2023 @11:57PM (#38731086)
Popular opinion* at least amongst the JS developers I’ve worked with for the last 10 years or so.
Re:Deep Cloning Objects in JavaScript, the Modern Way by vasergen on Friday December 22, 2023 @03:18AM (#38732122)
I used it mostly when I pass an object into a function I don't control, but I want to make sure that the original object won't be changed.
Re:Deep Cloning Objects in JavaScript, the Modern Way by giankam on Friday December 22, 2023 @03:26AM (#38732181)
I have an application with a big data structure built as a tree of objects. With deep cloning I can: - Provide undo/redo. I just clone the whole tree. - Load/Save from/to the database part of the tree. I load it in a separate object and then deep clone in place. - Do mass modifications to a part of the tree. A clone a copy, apply modifications and the clone back in place.

I could do some of the changes in place, but to optimize Vue reactivity I work on copies.

I use prototypes so only lodash works for me.