How to destroy an object in javascript?

11,736

I think the delete-Operator is what you are looking for:

delete acme.models.nomination;
Share:
11,736
Philip Murphy
Author by

Philip Murphy

UI Developer

Updated on June 04, 2022

Comments

  • Philip Murphy
    Philip Murphy almost 2 years

    I'm wondering how to properly destroy an object in Javascript that contains an array among other data.

    For example (this is the initial state of the object):

    acme.models.nomination = {
        recipients : [], // array will be added to later.
        awardType: {}, // this object will be filled out later.
        privacy: 'private',
        ...
    };
    

    As the application is used the nomination.recipients object will be added to, along with the other data elements. Is it enough to do the following to clear the complete object when finished with it:

    acme.models.nomination = {};
    

    or is this better (or overkill):

    acme.models.nomination.privacy = undefined;
    acme.models.nomination.awardType = {};
    acme.models.nomination.recipients = {};
    acme.models.nomination = {};
    

    I'm thinking that the former statement (i.e. acme.models.nomination = {}) is enough as this effectively makes the entire contents unreachable and hence eligible for garbage collection. However, I'd like to get other peoples opinions on this. BTW, the answer can be given in a modern browser context, let's say browsers post-Jan-2012, as I know memory management was a bit inconsistent in the past.

  • Admin
    Admin almost 12 years
    Note that this remove the object attribute (and hence removes one reference, not necessarily all). Not necessarily what OP wants.
  • Philip Murphy
    Philip Murphy over 11 years
    @micha149 Consider the following code snippet: ` var x = {}; x.y = { a: 1, b: function() {} }; delete x.y; // x.y is undefined now ` This means that properties a and b are eligible for garbage collection => all good. What about if there was an array of elements within x.y. Consider the following code snippet: ` var x = {}; x.y = { a: 1, b: function() {}, c: [1, 2, 3, 4, 5] }; delete x.y; // x.y is undefined now ` If we delete the parent property all children are eligible for garbage collection as all children are unreachable. Would you agree? Thanks
  • Philip Murphy
    Philip Murphy over 11 years
    Check out this one: perfectionkills.com/understanding-delete/#comment-57399 - this article is quoted at bottom of: developer.mozilla.org/en-US/docs/JavaScript/Reference/Operat‌​ors/… - sounds like we should be using null instead.