IsraGab
IsraGab

Reputation: 5175

JavaScript weird behavior when object deleted

I have done the following:

a = {a:1};
b = {b:1};

c = [a,b]

delete a;

Now I don't understand why c still have two object : [a, b] but when I try to print a, console give me: Uncaught ReferenceError: a is not defined

Seems like object isn't exist anymore, but it still exist in the array.

I also tried to print:

typeof a //"undefined"

typeof c[0] //"object"

I was sure that when assigned an object to a variable it assigned by reference. Seems that here object has been copied?

Upvotes: 1

Views: 57

Answers (2)

idmean
idmean

Reputation: 14865

The delete operator removes a property from an object.

That is, if you have an object const obj = { a: 56, b: 62 } and you perform delete obj.b, the b property will be removed and object will only be { a: 56 }.

Since you didn’t declare any variables, you’re implicitly working on the window object. You’re code is equivalent to:

window.a = {a:1};
window.b = {b:1};

window.c = [window.a, window.b]

delete window.a;

As you can see, you just added some properties to the window object and then delete one of them. However, you did not delete the object assigned to the property.

Any object in JavaScript will be kept until there’s no more reference to each. Here, there’s still clearly a reference to the object you expect to be deleted in the array assigned to window.c and the object is not destroyed. (And think about it: What would you expect to be in the array if the object had been deleted?)

Upvotes: 1

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

Unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references, see the memory management page for more details.

Read here

Even after you delete a the reference of a will be stored in c.

Hence c will always be of object type.

a = {a:1};
b = {b:1};

c = [a,b];

delete a;

console.log(c);

The above code will return:

[
  {
    "a": 1
  },
  {
    "b": 1
  }
]

But if you delete delete c[0].a then it will delete the a from array c :

a = {a:1};
b = {b:1};
c = [a,b];
console.log (delete c[0].a);
console.log(c);

The output will be:

[
  {},
  {
    "b": 1
  }
]

Upvotes: 1

Related Questions