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 most other programming languages JavaScript allows supports the concept of deep copy and shallow copy.
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.
No, it does not. When you assign a new object to the "original" array, this does not affect the 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With