Connecting Tech Pros Worldwide Help | Site Map

How delete works in JavaScript.

dmjpro's Avatar
Lives Here
 
Join Date: Jan 2007
Location: India (West-Bengal)
Posts: 2,451
#1: Aug 5 '08
Here is a code snippet i tried out.

Expand|Select|Wrap|Line Numbers
  1. var array = new Array(12,20,"Debasis Jana");
  2. alert(array.length);
  3. delete array.length;
  4. alert(array.length);
  5.  
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 ....

Expand|Select|Wrap|Line Numbers
  1. var o = new MyClass();
  2. for(i in o) if(o.hasOwnProperty(i)) alert(i);
  3. delete o.prop1;
  4. for(i in o) if(o.hasOwnProperty(i)) alert(i);
  5.  
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 ...

Expand|Select|Wrap|Line Numbers
  1. delete o.prop1;
  2. o.prop1 = null;
  3.  
what do these two mean?
I gone a mess. :-)
rnd me's Avatar
Expert
 
Join Date: Jun 2007
Location: Urbana IL
Posts: 411
#2: Aug 5 '08

re: How delete works in JavaScript.


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