0

What is the correct way to delete an object that is an argument in a function? I have the following example code :

var theObjects = new Object();
    theObjects['first'] = { x:0, y:0 };
    theObjects['second'] = { x:0, y:0 };
    theObjects['third'] = { x:0, y:0 };

function somefunc(obj){
    // that
    for(var k in theObjects){
        if(theObjects[k] == obj){
            delete theObjects[k];
        }
    }

    // or that
    delete obj;
}

$(function(){
    somefunc(theObjects['first']);
});

My guess is that the first way is right, because I delete the object itself. But on the other hand, objects are passed in a function by reference. So when I delete, do I get rid of the object, or the reference to it?

dodov
  • 5,206
  • 3
  • 34
  • 65
  • First off, don't use `new Object()`, just define your object, ie: `theObjects = {}`, secondly, you cannot compare two objects like this. They will not == (or ===) each other. – Jacques ジャック Dec 29 '15 at 20:53
  • @Jacques well the code as presented is passing one of the object properties, so `==` will indeed work. – Pointy Dec 29 '15 at 20:54
  • Good point. To clarify for @hdodov, objects will only equal one another if they point to the same place in memory. So passing the object in will work because it points to the same place in memory. However, `{ x:0, y:0 } == { x:0, y:0 }` returns false because they are two separate objects. – Jacques ジャック Dec 29 '15 at 20:59

1 Answers1

3

Your question is close to this answer:

Deleting Objects in JavaScript

"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."

delete only works on properties so the first way is correct. If the variable is defined in global scope however it will be a property of window and will also be deleted. So your line delete obj wouldn't do anything.

Here's a js fiddle to illustrate the point:

https://jsfiddle.net/oyyw7k5j/

Community
  • 1
  • 1
Paul Carlton
  • 2,785
  • 2
  • 24
  • 42