4 ms·
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 log
by madeofpalk 3y ago
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.
- dylan604 3y agoIsn'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.
- recursive 3y ago> 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.
- Akronymus 3y agoThe 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.
- jay_kyburz 3y agoWow, I never knew this.
- dylan604 3y agoto 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.
- jholman 3y agoWhat 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.
- jv22222 3y agoThat's just one of the reasons I always say... https://twitter.com/justinvincent/status/1714866433426067573 https://twitter.com/justinvincent/status/1714866433426067573
- cortesoft 3y agoYou have it opposite… if you change the object after logging, it will retroactively change the logged version.