Search code examples
javascriptobjectobject-reference

Does deleting an key from Object creates/returns new Object?


I need to delete an property/key from one object comparing the other as in the below example

    var Obj1 ={
        a : '1',
        b : '2',
        c : '3',
        d : '4'
    }

    var Obj2 ={
        a : '1',
        b : '2',
        d : '5'
    }

     for (const key in Obj1) {
        if (!Obj2.hasOwnProperty(key)) {
            delete Obj1[key];
        }
    }

I have two objects Obj1 and Obj2. Need to compare two Objects and remove the missing key in Obj1. that is I am removing key c from Obj1.

It is working as expected. What I am wondering is whether new Object reference is created for this Obj1 after deleting or the Object reference is same?

How to find that?


Solution

  • The object reference is the same, you're merely modifying it (as a commenter says).

    Deleting object properties changes the underlaying class that the VM generated. If this object is on the hot path, it has significant performance implications. The object shape (e.g. described here) is different, so the JIT compiler has to create a new class and ditch the old one and mess with the referrences. But aside for performance implications, it's not changing anything in our (js developers') world.