dodov
dodov

Reputation: 5844

Javascript - deleting an object as parameter of function

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?

Upvotes: 0

Views: 784

Answers (1)

Paul Carlton
Paul Carlton

Reputation: 2993

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/

Upvotes: 3

Related Questions