Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do objects pushed into an array in javascript deep or shallow copy?

Pretty self evident question...When using .push() on an array in javascript, is the object pushed into the array a pointer (shallow) or the actual object (deep) regardless of type.

like image 338
Travis J Avatar asked Dec 28 '11 20:12

Travis J


People also ask

Is JavaScript deep or shallow copy?

Like most other programming languages JavaScript allows supports the concept of deep copy and shallow copy.

Can you push an object into an array JavaScript?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.

Is arrays copy of a deep copy?

No, it does not. When you assign a new object to the "original" array, this does not affect the copy.

Does object spread deep copy?

The spread operator makes deep copies of data if the data is not nested. When you have nested data in an array or object the spread operator will create a deep copy of the top most data and a shallow copy of the nested data.


1 Answers

It depends upon what you're pushing. Objects and arrays are pushed as a pointer to the original object . Built-in primitive types like numbers or booleans are pushed as a copy. So, since objects are not copied in any way, there's no deep or shallow copy for them.

Here's a working snippet that shows it:

var array = []; var x = 4; let y = {name: "test", type: "data", data: "2-27-2009"};  // primitive value pushes a copy of the value 4 array.push(x);                // push value of 4 x = 5;                        // change x to 5 console.log(array[0]);        // array still contains 4 because it's a copy  // object reference pushes a reference array.push(y);                // put object y reference into the array y.name = "foo";               // change y.name property console.log(array[1].name);   // logs changed value "foo" because it's a reference      // object reference pushes a reference but object can still be referred to even though original variable is no longer within scope if (true) {     let z = {name: "test", type: "data", data: "2-28-2019"};     array.push(z); }  console.log(array[2].name);   // log shows value "test" since the pointer reference via the array is still within scope 
like image 86
jfriend00 Avatar answered Nov 10 '22 13:11

jfriend00