Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some use-cases of when `delete` has been very useful in JavaScript?

We have some questions here that discuss delete in a more abstracted way, but I'm looking for practical examples of when use of delete could be used, versus doing something such as setting the property to null or undefined.

The delete operator deletes a property of an object.

What's a case of a challenge faced somewhere, that delete was the best solution, versus something else?

like image 744
Incognito Avatar asked Aug 25 '11 15:08

Incognito


People also ask

What is the use of Delete in JavaScript?

The delete operator removes a given property from an object. On successful deletion, it will return true , else false will be returned.

Should I use Delete in JavaScript?

delete is the only true way to remove an object's properties without any leftovers, but it works ~100 times slower if you are using delete in loops. The alternative solution is setting the value to u n defined like object[key] = undefined . It doesn't fully delete the property, it just sets the value to undefined.

Which keyword is used to delete a property of an object in JavaScript?

delete keyword is used to delete properties of an object in javaScript. Note: Delete keyword deletes the both value of the property and property also.

Does delete return any value?

Does delete return any value? Explanation: The delete operator doesn't return any value. Its function is to delete the memory allocated for an object. This is done in reverse way as that new operator works.


1 Answers

When using an object as a hashmap, you can iterate over the object's properties using:

for (var key in obj) {
    // ...
}

If some properties of that objects were set to null, their keys would be included there. By using delete you can remove their keys completely.

like image 155
kapex Avatar answered Oct 03 '22 06:10

kapex