Understanding JavaScript 'delete' Operator with Objects

How does the delete operator work in JavaScript when deleting objects?

I’m a bit confused with how the delete operator functions. Consider the following code:

var obj = {
    helloText: "Hello World!"
};

var foo = obj;

delete obj;

After executing this code, I find that obj is now undefined, but foo still refers to the object that obj initially pointed to. I’m trying to understand why delete obj only affects the variable obj and not the actual object itself.

Is this behavior due to JavaScript’s Garbage Collector, which operates on a retain/release basis? Specifically, would the object be removed from memory only if there were no other references to it?

I would appreciate insights regarding the javascript delete object functionality.

I’ve been working with JavaScript for a while, so I can totally see where you’re coming from. The key thing to grasp is that the delete operator in JavaScript only works on object properties.

When you write delete obj;, you’re not actually removing the object itself—you’re trying to delete the variable reference named obj, which isn’t how delete works.

Since obj is just a reference, the delete operator simply breaks that reference, leaving the actual object still in memory as long as something else—like foo—still points to it. That’s why the foo variable keeps pointing to the same object, even after delete obj;.

Building on what Rima mentioned, this behavior ties into JavaScript’s garbage collection mechanism. JavaScript employs an automatic garbage collector that keeps track of object references in memory.

The delete operator does not interact directly with memory or the object itself; it only impacts references within the current scope. When you execute delete obj;, all it does is remove the reference held by the variable obj.

Since foo is still pointing to that same object, the garbage collector sees that the object still has an active reference. Therefore, the object won’t be collected until all references to it, including foo, are removed. This understanding is essential when working with the JavaScript delete object behavior.

To expand on this, there’s a fundamental difference between deleting an object’s property and attempting to delete a variable. When you use delete on an object’s property (like delete myObject.property;), the property itself gets removed from the object, and you can no longer access it.

However, when you use delete obj;, you aren’t targeting a property but rather a variable that holds a reference. JavaScript does not allow deleting variables declared with var, let, or const, so delete only breaks the reference, but the object itself remains in memory.

It’s crucial to remember that deleting properties affects the structure of the object, while deleting a variable simply impacts the link to the object, in line with how JavaScript deletes objects.