How delete works in JavaScript.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    How delete works in JavaScript.

    Here is a code snippet i tried out.

    [code=javascript]
    var array = new Array(12,20,"De basis Jana");
    alert(array.len gth);
    delete array.length;
    alert(array.len gth);
    [/code]

    Basically first i tried to delete the array then i did this to delete a property.
    It's not working, before this what i tried ....

    [code=javascript]
    var o = new MyClass();
    for(i in o) if(o.hasOwnProp erty(i)) alert(i);
    delete o.prop1;
    for(i in o) if(o.hasOwnProp erty(i)) alert(i);
    [/code]

    It's working, now my question is that how delete works in JavaScript?
    Basically JavaScript engine uses a garbage collector then why delete comes in?
    One more thing if i do ...

    [code=javascript]
    delete o.prop1;
    o.prop1 = null;
    [/code]

    what do these two mean?
    I gone a mess. :-)
  • rnd me
    Recognized Expert Contributor
    • Jun 2007
    • 427

    #2
    you typically can't delete native props like length.

    delete remove a property from an object. setting a property to null does just that: the object's property exists, it's value set to null.

    delete is useful for controlling inheritance, cleaning up data for presentation and archiving, and to a lessor extent, clearing memory.

    think of an object as folder whose files are the properties. setting something to null would be like a 0 byte file; it's still there, still shows up in the file explorer. deleting it would remove the file from the folder or the property from the object.

    Comment

    Working...