Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hard Copy vs Shallow copy javascript [duplicate]

Tags:

javascript

This may be an old question but I'm really curious about the nature of copying objects by reference as an assignment in javascript.

Meaning that if

var a = {}; 
var b = a;
a.name = "Renato";
console.log(b); 
Object {name: "renato"}

I'm kind of new to javascript and this really caught my attention to have a shallow copy as a default for Object assignment. I searched that in order to create a hard copy, you have to create a mixin. I was wondering why was this chosen as the default since it's transformation seems to be very implicit. Thanks!

like image 773
Renato Francia Avatar asked Nov 05 '16 01:11

Renato Francia


People also ask

Does JavaScript shallow copy?

Javascript does a shallow copy by default for the non-primitive data type(Object, Array, Functions, Math, etc.). There is no any funda of deep or shallow copy applicable for the primitive data types as they are immutable in javascript. There are basically known 6 primitive data types available.

Is shallow copy faster than deep copy?

Shallow copy is faster than Deep copy. Deep copy is slower than Shallow copy. 3. The changes made in the copied object also reflect the original object.

What is the difference between shallow copy and deep copy in JavaScript?

A deep copy occurs when an object is copied along with the objects to which it refers. Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object.

Is Copy () A shallow copy?

copy() function creates shallow copies of objects.


1 Answers

Objects and arrays are treated as references to the same object. If you want to clone the object, there are several ways to do this.

In later browsers, you can do:

var b = Object.assign({}, a);

If you want to go for a library, lodash provides _.clone (and _.cloneDeep):

var b = _.clone(a);

If you don't want to do either of those methods, you can just enumerate through each key and value and assign them to a new object.

Oftentimes it's valuable for them to be treated as references when passing through multiple functions, etc. This isn't the case for primitives like numbers and strings, because that would feel pretty counterintuitive in most cases.

like image 95
Josh Beam Avatar answered Oct 15 '22 07:10

Josh Beam