Search code examples
javascriptjavascript-objects

Referencing Object within Object Javascript Confusion


I am trying to create a reference to an object within an object, rather than creating a copy of it. I'm confused about reference vs. copy. What confuses me:

let master = {}
master['SomeObject'] = {a:"Something",b:"something"}
let subMaster = master['SomeObject']
subMaster['Test'] = true
console.log(master['SomeObject']['Test'])
//this WORKS as expected updating the original object
delete master['SomeObject']
console.log(subMaster)
//still shows content, and can continue to be manipulated? Shouldnt it show undefined?

Why does the reference still work even after deleting the original object? If I'm misunderstanding references, how can I make sure the original object is deleted so all references no longer work? I'm probably missing something fundamental and I appreciate anyones help!


Solution

  • delete does not physically delete the object from memory. It only removes that property from master. Since you are still referencing the object from your variable, and your variable has not fallen out of scope, the object still resides in memory.

    Per MDN:

    The JavaScript delete operator removes a property from an object