89

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.

3 Answers 3

152

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
1
  • 3
    Nitpicking: every value is pushed as a value; in the case of objects those values just happen to be "pointers" to the object.
    – deceze
    Commented Jun 21, 2021 at 15:18
50

jfriend00 is right on the mark here, but one small clarification: That doesn't mean you can't change what your variable is pointing to. That is, y initially references some variable that you put into the array, but you can then take the variable named y, disconnect it from the object that's in the array now, and connect y (ie, make it reference) something different entirely without changing the object that now is referenced only by the array.

http://jsfiddle.net/rufwork/5cNQr/6/

var array = [];
var x = 4;
var y = {name: "test", type: "data", data: "2-27-2009"};

// 1.) pushes a copy
array.push(x);
x = 5;
document.write(array[0] + "<br>");    // alerts 4 because it's a copy

// 2.) pushes a reference
array.push(y);
y.name = "foo";

// 3.) Disconnects y and points it at a new object
y = {}; 
y.name = 'bar';
document.write(array[1].name + ' :: ' + y.name + "<br>");   
// alerts "foo :: bar" because y was a reference, but then 
// the reference was moved to a new object while the 
// reference in the array stayed the same (referencing the 
// original object)

// 4.) Uses y's original reference, stored in the array,
// to access the old object.
array[1].name = 'foobar';
document.write(array[1].name + "<br>");
// alerts "foobar" because you used the array to point to 
// the object that was initially in y.
5
  • 2
    Interesting point about using new to "disconnect" the object reference.
    – Travis J
    Commented Feb 8, 2013 at 18:51
  • 2
    Downvote explanation? Hard to fix the issue if you don't let me know what it was.
    – ruffin
    Commented Nov 3, 2013 at 1:44
  • Why ping me? I upvoted this a long time ago and did like your answer. Here is a screen of the vote: i.imgur.com/AnDt98c.png
    – Travis J
    Commented Nov 3, 2013 at 6:14
  • 2
    Sorry @Travis -- collateral damage for SO not having another way for me to communicate with the recent anonymous downvoter that came by in the last week or two. I didn't expect it came from you, esp. with your positive comment. Sorry for the unfortunate spam your way, and thanks for staying on top of your question!
    – ruffin
    Commented Nov 4, 2013 at 14:42
  • 2
    That was actually a misunderstanding on my part. My bad. Your comment showed in my notifications and I thought it was directed at me because I didn't realize that as the OP all comments show as notifications.
    – Travis J
    Commented Nov 4, 2013 at 15:39
4

JavaScript: Create a Deep Copy of an Object in 2023

Do NOT use Object.assign() in JavaScript to copy or clone objects! It creates a shallow copy of your object and will assign deep objects to reference pointers in your copy!

You have two choices.

Use the older, more reliable JSON trick:

const obj1 = JSON.parse(JSON.stringify(YourObject));

Or try the new & improved structuredClone() method. Warning: This only works for users who have updated their evergreen browsers since 2022! No Internet Explorer or Edge Trident browser support!!

const obj2 = structuredClone(YourObject);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.