kussberg
kussberg

Reputation: 559

Javascript delete object from object

I have following function that should delete an object in object under following id:

contactDeleteCounter++;
console.log(orderContactIds);
console.log(deletePosition);
console.log(orderContactIds[deletePosition]);
delete orderContactIds.deletePosition;
console.log(orderContactIds.deletePosition);
console.log(orderContactIds);
console.log(deletePosition);

The problem is that i everything works great in Chrome, but Firebug in Firefoxshows me following output:

Object { 0={...}, 1={...}, 2={...}}
2
Object { id= "20" , type= "1" }

undefined
Object { 0={...}, 1={...}, 2={...}}
2

As you see, the attribute is undefined, but when i look in the object, it is still there...?

Upvotes: 0

Views: 162

Answers (2)

kussberg
kussberg

Reputation: 559

The answer is to create a callback and to make async Jquery:

function deleteCallback(deletePosition) {
    $.ajaxSetup({
        async : false
    });
    console.log(orderContactIds);
    console.log(deletePosition);
    console.log(orderContactIds[deletePosition]);
    delete orderContactIds[deletePosition];
    console.log(orderContactIds.deletePosition);
    console.log(orderContactIds);
    console.log(deletePosition);
    $.ajaxSetup({
        async : true
    });
}

Upvotes: 1

David Fariña
David Fariña

Reputation: 1594

The delete operator deletes only a reference, never an object itself. If it did delete the object itself, other remaining references would be dangling, like a C++ delete. (And accessing one of them would cause a crash. To make them all turn null would mean having extra work when deleting or extra memory for each object.)

Since Javascript is garbage collected, you don't need to delete objects themselves - they will be removed when there is no way to refer to them anymore.

It can be useful to delete references to an object if you are finished with them, because this gives the garbage collector more information about what is able to be reclaimed. If references remain to a large object, this can cause it to be unreclaimed - even if the rest of your program doesn't actually use that object.

Upvotes: 0

Related Questions