Deleting object properties conditionally

I have an object that may or may not have properties that I want to remove; properties are added at runtime. This is how I write the code:

if (MyObject.hasOwnProperty("SomeProperty")) {
   delete MyObject['SomeProperty'];
}

      

If I remove the condition to check if the property doesn't exist the code doesn't crash, but I'm wondering if it's just because I'm running it in Chrome or if it's valid javascript. In other words, can I write delete MyObject['SomeProperty'];

without instruction .hasOwnProperty

and be fine even if the object has no properties.

+3


source to share


1 answer


The condition is not needed here. The operation will delete

do nothing if the property does not exist on the object. It also doesn't remove inherited properties.



Delete documentation

+4


source







All Articles