12 ms·
Deep-copying in JavaScript
- kevincennis 9y agoJavaScript is absolutely not pass by reference. let a = 1; function foo( a ) { a = 2; } foo( a ); console.log( a ); // 1
- aeharding 9y agoEDIT: I am wrong. Below quote is irrelevant. I misunderstood the term "pass by reference", and confused it with mutable entities. It is for objects, not primitives. > JavaScript has 6 primitive data types: string, number, boolean, null, undefined, symbol (new in ES6). With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable. https://stackoverflow.com/a/13266769/1319878 https://stackoverflow.com/a/13266769/1319878
- amarshall 9y agoThe object is still passed by value, however the object itself contains references, which may be mutated. If objects were pass by reference then you’d end up with {a: 2} at the end: let a = {a: 1} function foo(a) { a = {a: 2} } foo(a) a //=> {a: 1} Don’t confuse passing a mutable entity by value with pass by reference.
- mnarayan01 9y ago> The object is still passed by value, however the object itself contains references, which may be mutated. This would imply that: var v = 1; (function (o) { o.a = 2; }({ a: v }); console.log(v); // => 2 The whole "objects are pass-reference-by-value" is obviously annoying and confusing, but we're kind of stuck with it.
- shkkmo 9y agoApparently there is another term (which I hadn't heard) which is: call-by-sharing https://en.m.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing https://en.m.wikipedia.org/wiki/Evaluation_strategy#Call_by_...
- kevincennis 9y agoThat's irrelevant. Look, same example but with an object. let a = { bar: 'baz' }; function foo( a ) { a = { beep: 'boop' }; } foo( a ); console.log( a ); // { bar: 'baz' }
- n0us 9y agoAnother way to think about it is that you just get a new reference to the same object, inside foo you are changing what 'a' refers to instead of what 'b' refers to. Using 'let' to declare 'b' is not necessary and using 'const' works just as well. $ node > const b = { bar: 'baz' } > function foo(a){ a = {beep: 'boop'}; } > foo(b) > console.log(b) { bar: 'baz' } >
- lowkeyokay 9y agoI thought this was just a matter of scope. a declared outside of the function is not the same as the one declared as a parameter.
- LoSboccacc 9y agothat answer doesn't concern with the pass-by semantic, only with the primitive/object semantics. this is the gist of the issue, fetched from http://javadude.com/articles/passbyvalue.htm http://javadude.com/articles/passbyvalue.htm about java but exemplifies perfectly the pass by reference semantics: "If you can write such a method/function in your language such that calling Type var1 = ...; Type var2 = ...; swap(var1,var2); actually switches the values of the variables var1 and var2, the language supports pass-by-reference semantics." as java javascript is reference-by-value
- jerf 9y agoNowadays, everything is pass-by-value. The only question is whether a reference or a pointer is one of the things that can be passed by value, or if everything passed is always a copy. An exception to pass-by-value would be Forth; in the case of stack-based languages there really isn't a "pass" going on at all. But everything copies something for every non-inlined function call nowadays. Another instance where it's less obvious what is going on is a truly immutable language like Erlang or Haskell, where the "value" is quite likely still being passed via a pointer, but that's only relevant from the point of view of considering garbage collection behavior. This makes the old "pass-by-value vs pass-by-reference" terminology vestigial to the modern software engineer, which is why the only place you'll encounter it is in school courses. A better way of understanding the modern issues is to ask what powers a passed-in value has and just ignore the old question.
- shkkmo 9y agoWhat are you talking about? PHP has pass-by-reference: http://php.net/manual/en/language.references.pass.php http://php.net/manual/en/language.references.pass.php
- jerf 9y agoAnd the references are passed by value. There are two places you can find in RAM that will contain that reference, which once you penetrate through the abstractions and wrappers, will be a pointer; that second location is the reference that was passed by value. A reference is basically a pointer that the language prevents you from doing pointer arithmetic on, and in many languages such as PHP, is simply automatically dereferenced for you. The reason why I brought up languages like Forth is that there really did used to be languages that did not actually "pass" things by value. Forth had a true pass-by-reference, in which there is no second copy of anything, neither the value, nor a pointer to the value. Now it's a dead distinction, in the sense that pass-by-value and pass-by-reference used to be distinguishing, because everything is copying something. Which is why the distinction is sort of confusing to try to apply to modern languages, and produces lots of heat but no light; it's dead, inapplicable to the modern language landscape. The proper question to be asking is what permissions/privileges are passed by a function's parameter, whether you're allowed to modify it and have the modifications visible to the caller, whether you're not allowed to modify it at all (immutable languages, for instance), or whether there's an entire ownership system around what the passed-in value represents (Rust), not whether or not something was copied when the function call was made. Trying to answer this question in terms of "pass-by-X" doesn't help, if for no other reason than pass-by-X implies there's only two possibilities, and I outlined three classes of possibilities above, each of which can have their own further nuances. Is Rust pass-by-reference or pass-by-value? Well, the question is invalid, in either the original or the modern mutation of the meaning.
- jordache 9y agoDon't know why you are being down voted. The author claimed EVERYTHING is pass by reference, which is false.
- williamdclt 9y agoIt's not even close, nothing is passed by reference!
- jordache 9y agoobjects? I don't care about low level engine implementation details. I'm saying from the dev's perspective, it's effectively pass by reference.
- pjmlp 9y agoIt is only pass by reference if what ends up in the call stack is the address of the actual variable on the caller side, not what it points to.
- globuous 9y agoWow, you got downvoted for being 100% right. Nothing in the first sentence nor the first code example is right. I haven't bothered to look at the rest ^^ JS doesn't pass everything by reference. As you've shown in your code example. And JS doesn't actually pass anything by reference as you and Amarshal have shown in your comments (which I knew, but didn't at the same time... Thanks for enlighting me guys!). But what's mind blowing is that the code example given doesn't actually have anything to do with pass by ref of value. It's checking that the attributes of objects are reference based. It's not actually checking the function argument. Just an attribute of the argument. I've upvoted your comment and your subcomment/reply. Not that you or anyone cares. They're just points. But it's a shame your comment is being greyed out.
- chasingtheflow 9y agoIt is for objects, just not for primitives.
- williamdclt 9y agoNo. Object are passed by value. Exact same example apply: let a = {key: 'a'}; function foo( a ) { a = {otherKey: 'b'}; } foo( a ); console.log( a ); // {key: 'a'}
- MJSplot_author 9y agoBut it is also true that: let a = {key: 'a'}; function foo( a ) { a['otherKey'] = 'b'; } foo( a ); console.log( a ); // {key: 'a',otherKey: 'b'}
- shkkmo 9y agoYes, which together with the other example shows that javascript uses pass-reference-by-value, as explained elsewhere on the thread.
- williamdclt 9y agoYes, because "a" is not an object, it is a reference to an object. This reference is passed by value. This kind of thing is why I'd recommand everybody to know C: when you know pointers there's no magic anywhere anymore
- teamonkey 9y agoCould you give an example in C of how the above works?
- pjmlp 9y agoSomething like this, without any kind of error checking being done. #include <stdlib.h> // assume some hash table library, exercise for the reader typedef struct{} *hashtable_t; extern hashtable_t hashtable_init(void); extern void hashtable_put(hashtable_t hashtable, const char* key, const char* value); extern void hashtable_dump(hashtable_t hashtable); typedef struct { hashtable_t table; } data_t; void foo(data_t* a) { hashtable_put(a->table, "otherKey", "b"); } int main(void) { // let a = {key: 'a'}; data_t* a = (data_t*) malloc(sizeof(data_t)); a->table = hashtable_init(); hashtable_put(a->table, "key", "a"); foo(a); // console.log( a ); hashtable_dump(a->table); return 0; } The function foo() gets the numeric value of the a pointer, thus a parameter inside foo() points to the same memory location. If C had pass-by-reference, it would be possible to give (implicitly) the memory location of the local variable a in main() instead. For example, like in Pascal (var) or C++ (& in function declaration).
- rising-sky 9y agoYou are correct, but it would so help to explain to the reader what the correct evaluation strategy employed by JavaScript is: call-by-sharing. https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sh...
- ghusbands 9y agoNot quite accurate. The primitive types (string, number, null, boolean, symbol, undefined) are passed only by value. Also, the page you link to says "the terminology is inconsistent across different sources", so it doesn't seem an ideal choice. Javascript is pass by value, with some of those values being references.
- kmill 9y agoWould you know that some Javascript engines store primitives on the heap, so potentially it can all be described as call-by-sharing? Then again, they are immutable, so it is indistinguishable from call-by-value. I think making these distinctions is somewhat asinine and that it doesn't really do more than make people aware that the function call interface actually has some interesting design considerations. It's sort of like "ok, we have decided whether a hamburger is a sandwich. Now we can finally do the thing that desperately depended on this decision, which was, uhh..."
- zzzcpan 9y agoFrom a user perspective most languages make a mess out of these things and confuse people. In Javascript certain things are declared in a similar way, but some behave like values and some behave like references. Which makes it both pass-by-value and pass-by-reference.
- shkkmo 9y agoI believe that javascript always uses pass-reference-by-value, but simple types are immutable, which means that pass-reference-by-value is functionally identical to pass-by-value since there is no way to make changes to the immutable referent.
- pjmlp 9y agoWrong from CS point of view, references are also pass-by-value on JavaScript. If JavaScript allowed pass-by-referece, we would be able to do the following, function swap(x, y) { let c = x x = y y = c } let a = {a: 6, b: 7} let b = {c: 8, d: 8} swap(a, b) console.log(b) // Object {a: 6, b: 7} Meaning, pass-by-reference means being able to actually change the "pointer" used by the local variable.
- zzzcpan 9y agoI understand what you mean, but consider this to be an incorrect view on these things. They are not about CS, but about user experience.
- pjmlp 9y agoThe incorrect view is to teach wrong concepts just because some people rather learn based on gut feeling, than taking the effort to learn it properly.
- j4ship 9y agounless you pass an object ..... then it is its partial pass by reference. Is HN the place to get wrong information, this is an example of what is going on here. How is this not completely downvoted out of oblivion https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language https://stackoverflow.com/questions/518000/is-javascript-a-p...
- Sawamara 9y agoPrimitive types and properties that are primitive types are pass by value, objects and functions are pass by reference.
- windwake12 9y agoThere's no difference let a = function bar() { }; function foo( a ) { a = 2; } foo( a ); console.log( a ); // bar
- k2xl 9y agoIt's still pass by value. The value of the object happens to be a reference to a memory location. A primitive also points to a memory location too.
- andrewstuart2 9y ago"By reference" means different things to different people. The most accurate statement I've found is that JavaScript, much like Java, passes reference-by-value. Everything is passed by value, but if your value is an object, then the new scope gets a copy of the reference. If you modify the object by dereferencing (that is, `a.foo = "bar";`), your modifications to the object persist outside of your scope. This is an important understanding to have when working with JavaScript.
- pjmlp 9y agoEverything is passed by value. A numeric value is put into the call stack. Which in the case of references happens to be the address of pointee. It is only pass by reference, if what is put into the call stack is the address of the actual variable on the caller stack holding the data.
- andrewstuart2 9y agoIsn't that what I said? That's what I was trying to say, at least, but keeping the language more js-oriented.
- ZeroBugBounce 9y agoI'm not the parent commenter but yes, you both made the same distinction as far as I can tell.
- Stratoscope 9y agoIt doesn't help us understand the language if we try to shoehorn JavaScript's behavior into one of two buckets: "pass by value" or "pass by reference." As you mentioned elsewhere, these terms are well defined in computer science. But how JavaScript works doesn't match either of them. It only creates confusion to force JavaScript assignment and parameter passing into one of those two categories. This is what has led to the widespread misconception that "primitives are passed by value, and objects are passed by reference." We're not implementing JavaScript engines here, we're programming in JavaScript. Implementation details like addresses and pointers are unknown to our code. They may differ from one JavaScript engine to another, and even during a single run of your program as the engine decides on the fly how to optimize or de-optimize your code. What matters is the observable behavior from the point of view of the running JavaScript code. There are a few ways you could describe that behavior, such as my notion of a new "name" that refers to an existing "thing", or shkkmo's and andrewstuart2's "pass a reference by value". But it's not "pass by value" as that term is understood in other programming languages such as C/C++.
- blitmap 9y agoI thought this was because Javascript (by design) doesn't warn about shadowing identifiers.
- tw1010 9y agoTackling the toughest challenges of our generation.
- tlb 9y agoI use lodash.cloneDeep for this. https://lodash.com/docs/4.17.4#cloneDeep https://lodash.com/docs/4.17.4#cloneDeep. It has variants to munge the object while copying.
- deleted 9y ago[deleted]
- streptomycin 9y ago"Deep copy" and "structured clone" are not synonymous. A structured clone is one specific type of deep copy, and it has a variety of quirks. It's not clear to me why anyone wants structured clone as opposed to some other kind of deep copy, except if you were polyfilling some API that demands it like I did here https://github.com/dumbmatter/fakeIndexedDB https://github.com/dumbmatter/fakeIndexedDB There are plenty of more reasonable deep clone functions available, for instance the Lodash one someone posted in another comment https://lodash.com/docs/4.17.4#cloneDeep https://lodash.com/docs/4.17.4#cloneDeep
- Sammi 9y agoI'd like to see the benchmark in the article include the lodash cloneDeep function.
- xamuel 9y agoThe solutions presented fail if one of the values in obj is a function. E.g., JSON.parse(JSON.stringify({foo:x=>x})) returns {}. It's not intuitively obvious what the "correct" solution ought to be. If cloner is a deep-cloning function, and f is a function, which of the following should be true? 1. cloner(f) === f? 2. For all ...args, cloner(f)(...args) === f(...args)? 3. For all ...args, cloner(f)(...args) === cloner(f(...args))? 4. For all ...args, cloner(f)(...args) === f(...args.map(cloner))? 5. For all ...args, cloner(f)(...args) === cloner(f(...args.map(cloner)))? 6. Something else entirely?
- dassurma 9y agoOhai. Author here. That’s indeed one of the trip-wires. So is that any kind of prototype is lost. The point of the structured clone algorithm is to make values transferable to other realms, so functions are actively ignored. Most of the time, I think that is “good enough”.
- deleted 9y ago[deleted]
- shkkmo 9y agoCan you fix your first statement: "JavaScript passes everything by reference" which is incorrect? see: https://jsfiddle.net/t73ykuj0/ https://jsfiddle.net/t73ykuj0/
- zakember 9y agoCan you please explain why this behavior is happening in this jsfiddle, or point me to a link that can help me understand this better?
- shkkmo 9y agoThe term for what Javascript does is pass-reference-by-value or pass-by-sharing: https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sh...
- tobr 9y agoIs the `await` used in the last two examples a typo? They're not asynchronous are they?
- dassurma 9y agoSo, it’s me being lazy and copy-pasting, but you can use await on synchronous functions, too. It’s a no-op :D
- phpnode 9y agoNot a no-op, it wraps the awaited value in `Promise.resolve()`: async function foo() { const a = await {then(resolve) { resolve(123); }}; console.log(a); } foo();
- pitaj 9y agoIndeed, you don't use `await` on functions either, it's used on promises. In fact, when used on a non-promise, it still waits an extra loop cycle before resolving and continuing the async function.
- heisenbit 9y agoHow does inmutable-js fit into this discussion? My limited understanding is it defers the copy decision and then can limit it to the area needed. Wouldn't that lead in most cases to a better performance?
- olfactory 9y agoI'm wondering this too.
- dlbucci 9y agoIf you have immutable objects (doesn't even have to be ImmutableJS, you can just decide to never mutate object properties), then there's really not even a need for cloning at that point. The reason you would clone an object is to avoid mutating the original object, which you don't need to worry about when everything is immutable.
- DiThi 9y agoExcept that you need to copy _something_ at some point to modify values (or more precisely, having another object that is the same but with X change). In theory everything is re-created with a change, but in practice only the changed objects are copied.
- danmaz74 9y agoImmutable objects aren't very useful if you can't create mutated copies...
- Jach 9y agoI don't know the details of immutable-js but generally an immutable 'deep copy' shouldn't be different than a 'copy' that you'd normally get by e.g. passing the thing by value. Two symbols point to the same root that defines the data structure, the symbols are value-equal, but not id-equal (at the symbol comparison level). The usual concerns about deep copying don't really apply, since if you try to mutate either of them, neither of them will be affected, but a new piece of data will be created that has an id-different path to the root of the structure but everything unmodified out of that path is still id-equal.
- kin 9y agoI would never deep copy using any of those methods. Can't you just write your own recursive version? I remember plenty of examples on jsPerf (site not working at the moment) including my own that significantly outperformed JSON parse/stringify.
- BinaryIdiot 9y agoYeah I'm confused as most of those methods, like postMessage, stringifies things anyway. I simply iterate other object properties to make a copy of a full object. I've never run performance tests but surely that's faster than parsing an object into its string representation then parsing it back into the language, no?
- dassurma 9y agoAs I explain in the article, postMessage does not stringify. It runs the structural clone algorithm, as per spec. Otherwise things like ArrayBuffers, Sets et al. would not make it to the other side.
- tlack 9y agoThe problem is figuring out if you're in a looping/cycling data structure or not. JSON.stringify and friends often already have code to deal with that, and it's quite complex in pure JS because there is no "object id" function.
- smt88 9y agoBecause JS doesn't clone natively and library behavior varies somewhat, our team has started to consider deep-copying and cloning to be a smell. It forces the maintainer to figure out how exactly the copying/cloning is going to work, and it also creates nasty bugs when modifying a class without knowing it'll be copied or cloned somewhere. We instead only use immutable, plain ("POCO" or "POJO" in other languages) objects for data. If you want to copy an object, you have to call the same functions to change it that you called on the original. If the functions are deterministic (as they should be), then you get identical objects at the end. Our code base is effectively functional, even though we still use objects as our syntactic sugar (addOwner(car, user) becomes car.addOwner(user), etc.)
- Stratoscope 9y agoOn the "pass by value" vs. "pass by reference" controversy, I see two issues here: First, these terms have specific meaning in other languages such as C++, but JavaScript's behavior does not match either of their definitions. Second, there is a widespread myth that JavaScript passes primitive values and objects in two different ways. It doesn't. They work exactly the same, and making an artificial distinction between them is not useful. I find it helpful to make up some new terminology, so my thinking isn't led astray by implied comparisons with other languages. I like to talk about names and things. A name is a variable name or a parameter name. A thing is any object or primitive value: anything that you can pass as a function argument or use on the right side of an assignment operator. A name always refers to one thing. A thing can have multiple names. When you pass an argument into a function, or when you use the assignment operator, you are giving a new name to an existing thing. If the name already referred to some other thing, that connection is lost. The name now refers to the new thing, and only to the new thing. Everything works this way, primitives and objects alike. The reason it's often claimed that objects are passed into a function by reference, while primitives are passed by value, is that we instinctively write different code for the two cases. That different code is what leads to the notion that objects and primitives are treated differently. If you pass an object into a function and you want to add or change a property of that object, you'll naturally write: function foo( obj ) { obj.myprop = 42; } But if you know the function is going to receive a primitive value, you won't write this: function foo( val ) { val.myprop = 42; } If you do, you'll find out soon enough that it won't work. It will throw an exception in strict mode, or fail silently in non-strict mode. Instead you may write: function foo( val ) { // Do stuff here with val val = 42; // Do stuff here with the *new* val, which isn't the old val } The reason the functions behave differently is not because JavaScript passes primitives and objects differently. It doesn't; they are all treated the same. But primitives are immutable. They have no properties that we can change. We know that, or we find out if we try, so we simply don't write code that tries to change a property of a primitive value. It isn't the JavaScript language that treats objects vs. primitives differently when passed into a function or when used in an assignment statement. We programmers do, by writing different code for the two. (Edited for clarity)
- shkkmo 9y ago
- potch 9y agoJavaScript is pass-by-reference for all Objects and Arrays. Value types are pass-by-value. let obj = {a: 1} function foo(arg) { return obj === arg; } foo(obj) // true The === operator operates on object not by comparing their value, but by comparing their memory reference [1]. A function argument variable can be reassigned using = in the function body, but that changes which location in memory the reference points to and isn't somehow "proof" of pass-by-value. [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality_operators https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- shkkmo 9y agoJavascript is pass-reference-by-value for Objects and Arrays, see: https://jsfiddle.net/t73ykuj0/ https://jsfiddle.net/t73ykuj0/ If javascript was pass-by-reference for Objects, your code could read: arg = {a: 2}; return obj === arg; and still behave the same.
- andrewstuart 9y agoIf you find yourself deep copying then you're about to level up your JavaScript career. The actual answer is not to find out how to deep copy reliably. The actual answer is don't deep copy - instead you should be using immutable data structure - check out immutablejs. This will solve the problems that you are trying to address by deep copying. Sticking with deep copying will only increase your pain and decrease your software reliability.
- acemarke 9y agoYeah, generally what's needed for data updates is _nested shallow copies_, not a deep copy. I talked about this in the "Immutable Update Patterns" section of the Redux docs [0], and the articles in the "Immutable Data" section of my React/Redux links list [1] give more examples of how to handle data immutably in JS. There's dozens of immutable update utility libraries available [2]. The one that I'm really excited about right now is a new library called Immer [3], from MobX author Michel Weststrate. It uses ES6 proxies to let you write normal mutative code in a callback, then applies the updates immutably. It looks like it should simplify a lot of common immutable update use cases, like in Redux reducers. [0] https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePa... [1] https://github.com/markerikson/react-redux-links/blob/master/immutable-data.md https://github.com/markerikson/react-redux-links/blob/master... [2] https://github.com/markerikson/redux-ecosystem-links/blob/master/immutable-data.md#immutable-update-utilities https://github.com/markerikson/redux-ecosystem-links/blob/ma... [3] https://github.com/mweststrate/immer/ https://github.com/mweststrate/immer/
- littlestymaar 9y agoWhat's a nested shallow copy, and how is it different from a deep copy ?
- acemarke 9y agoA shallow copy means creating a new object (or array), where all of the fields or array values point to the same references as the original: const original = {a : {a1 : 42}, b : {b1 : 99} }; const shallowCopy = {...original}; console.log(shallowCopy.a === original.a); // true A deep copy means creating new objects at _every_ level of nesting: const deepCopy = _.cloneDeep(original); console.log(deepCopy.a === original.a); // false To properly do an immutable update for `original.a.a1`, you'd need to copy each level of nesting, and overwrite the fields in that chain: const updated = { ...original, a : { ...original.a, a1 : 123 } }; console.log(original.a === updated.a); // false console.log(original.b === updated.b); // true
- frwhlr 9y agoI think it is almost unbelievable that the ESxx train continues to expand the language with ever more features, while at the same time there is still no native method to deep-copy an object.. Almost everything in JS is an object, but there is no reliable way to copy one.. Feels like an epic failure to me. Would it not be an idea for the ESxx team to finally fix this core issue for the first upcoming release?
- dassurma 9y agoI kinda agree, although I think "epic failure" is a bit strong. But that's exactly why I am volunteering to work on the spec to move that functionality into the HTML spec, and then hopefully also to ECMAScript.
- taco_emoji 9y agoWhy is deep copy so essential? Deep copy is the wrong solution to your problem 99% of the time, IMO.
- frwhlr 9y agoI think spamming mutable objects around in your codebase is asking for trouble. I'd be really happy to be able to do something like this: foo( Object.copy(barObj) ); I mean, why would you send your state's mutable object as argument if you're 100% sure you don't want it to be changed?
- taco_emoji 9y agoBecause copying is expensive. If mutability is the issue, use Object.freeze(), or define properties with Object.defineProperty() setting writable to false.
- fleitz 9y agoBecause it allows you to keep your shitty mutable functions... because the solution to any problem is never to fix the actual problem but to patch around it...
- 9y ago
- takinola 9y agoFor fun and games, try deep copying event objects. Spoiler alert: it doesn't work in ways that are not immediately obvious. Hours of my life I will never get back...
- klokoman 9y agoIn some cases you can assign the object you want to copy as the [[prototype]] of another object, this way you delegate what you don't want to change and change what you want in the "copy" via assignments
- codeisawesome 9y ago> If you don’t expect cyclic objects and don’t need to preserve built-in types, you get the fastest clone across all browsers by using JSON.parse(JSON.stringify()), which I found quite surprising. I wonder if that’s because browser devs know by now that this is a widely used technique and hence optimise for it.
- Havelock 9y agoI suspect it is because JSON.parse and JSON.stringify are more commonly used methods and therefore see more optimization than methods use less.
- ricardobeat 9y agoMissing from the benchmarks is simple deep copying: function deepClone (obj) { var clone = {} for (var key in obj) { if (obj.hasOwnProperty(key)) { var value = obj[key] switch (Object.prototype.toString.call(value)) { case '[object Object]': clone[key] = deepClone(obj[key]); break case '[object Array]' : clone[key] = value.slice(0); break default : clone[key] = value } } } return clone } This is 5-10x faster than the JSON trick in WebKit: http://jsben.ch/W0ciO http://jsben.ch/W0ciO (naive implementation, but covers 90% of uses, see lodash for the full mess: https://github.com/lodash/lodash/blob/master/.internal/baseClone.js https://github.com/lodash/lodash/blob/master/.internal/baseC...)
- drodgers 9y agoI believe that it's faster, but only because it's not actually deep-cloning. This: value.slice(0); is a shallow clone; it makes a new array, but doesn't clone it's contents.
- ricardobeat 9y agoHence being a 'naive' implementation. You can replace that with something like `deepClone(value)` + implement copying for different types, ultimately you'll end up with code like lodash's.
- drodgers 9y agoIt's not just naive though, it's wrong; it won't even give you new objects although it seems like it's meant-to: a = [1, {foo: "bar"}]; b = a.slice(0); b[1].foo = "baz"; console.log(a) > [1, {foo: "baz"}] console.log(b) > [1, {foo: "baz"}] A naive implementation would do this: case '[object Array]' : clone[key] = value.map((item) => deepClone(item)); break And would thus be slower.
- ricardobeat 9y ago
- 11235813213455 9y agoJSON.parse(JSON.stringify(o)) is super bad, it can throw for a circular object for example. It should be done cleanly with a recursive function: deepMerge({}, obj)
- peter_retief 9y agoI was surprised how difficult it was to make a deep copy with javascript, (I did try JSON.parse) but finally decided to rewrite the logic without deep copy. Its a great article, shed some light on an interesting programming question
- tobyhinloopen 9y agoThis is why JavaScript is the biggest joke of web development. And error handling. Can we please stop using it
- chatmasta 9y ago“Deep copy” is a code smell and attempts to implement it will lead to pernicious bugs. Either you’re copying data, in which case it should be serializable to and unseriazable from JSON, or you’re copying objects, in which case you should think about what you’re really trying to achieve. There is usually a better solution.
- xg15 9y agoSomewhat OT: If you click through, you can find the original Twitter conversation that prompted this posting [1]. In that conversation, an interesting point about "optimizing away" string representations was brought up: [2, 3] > Interesting! How is this better or worse than the usual trick of `JSON.parse(JSON.stringify(obj))` ? (...) My idea was that the browser could detect that the string is immediately parsed anyway and just interpret the two function calls as "deep copy this object for me". I had thought about somethig like this in the context of innerHTML a whole ago. Generally, there are a lot of places in the DOM where can modify an object not by setting properties, but by getting a string representation of the object, modifying that string, then feeding the new string back to the browser for reparsing. Examples are document.cookie, css properties and of course innerHTML. In those cases, an optimisation like the above sounds like it could actually make sense. E.g., if someone abused innerHTML like this: for (let i = 0; i < data.length; i++) { myList.innerHTML = myList.innerHTML + "<li>" + data[i] + "</li>"; doSomethingWith(myList.lastChild); } a naive implementation would have to serialize, parse and recreate the whole object tree for each iteration of the list. However you could probably optimize it by having innerHTML return some special object that only "looks" like a string but somehow keeps track of its mutations internally. When the object is fed back to innerHTML later, the browser could use the internal properties to mutate the DOM instead of recreating it. I'm curious, does anyone know if optimisations like this are actually used? [1] https://twitter.com/DasSurma/status/955484341358022657 https://twitter.com/DasSurma/status/955484341358022657 [2] https://twitter.com/sergiomdgomes/status/955484966313488384 https://twitter.com/sergiomdgomes/status/955484966313488384 [3] https://twitter.com/moritz_kn/status/956444334970343424 https://twitter.com/moritz_kn/status/956444334970343424