Object copied to second property via reference persists even after original property deleted? Object copied to second property via reference persists even after original property deleted? javascript javascript

Object copied to second property via reference persists even after original property deleted?


...I am late to the party? Here is my take on explaining it (Read the other answers as well, this is just to support those answers with a visual representation):

  1. Initialization of the empty object a with another object (value:true).

enter image description here

  1. Assigning the empty object a with a property b referring to the other object (value:true).

enter image description here

  1. Assigning the object a with a property c referring to the same object (value:true).

enter image description here

  1. Deletion of the key b, thus a.b no longer refers to the sub-object (value:true).

enter image description here

  1. Final representation of the main object a.

enter image description here

So we can easily see by visual representation how the sub-object was being preserved :)


No, this is not a bug in JavaScript.

What you are doing with a.c = a.b is that you are creating another link to the same object, meaning that both a.b and a.c are referencing the same sub-object {val: "rawr"}.

When you do delete a.b, you are not removing the sub-object, you are only removing the a.b property from a. This means that a.c will still reference the same object.

If you were to delete the a.c property as well, then the sub-object will vanish.


There are two things to note, first, as said in other answers, the delete keyword removes a property only for the object through which you go to access the property.

The second thing to note is that JavaScript does not pass by reference, ever. It always passes as a value, values are sometimes references.

For instance:

var a = {   someObject: {}};var someObject = a.someObject;someObject = 'Test';console.log(a.someObject); // outputs {}

In a language which passes by reference this would probably cause an error because it often implies strong variable typing.