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?

3
  • 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. Commented Dec 29, 2015 at 20:53
  • @Jacques well the code as presented is passing one of the object properties, so == will indeed work. Commented Dec 29, 2015 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. Commented Dec 29, 2015 at 20:59

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.