Languages
[Edit]
EN

JavaScript - how to clear object

6 points
Created by:
Olivier-Myers
514

In this article, we would like to show you how to clear an object in JavaScript.

The below examples show solutions that:

  1. assign new empty object ({}),
  2. delete the object's properties.

Solution 1

Edit

In this solution, we create a new memory location with an empty object ({}) and we point existing object to that location.

Runnable solution:

Notes:

  • in that approach, the object cannot be const,
  • that approach changes variable reference.

 

Solution 2

Edit

In this section, we use for loop to iterate over object properties and delete them.

Note: that approaches are slow when we empty large objects.

2.1. for..in loop solution 

Edit

Runnable solution:

2.2. Object.keys() method solution

Edit

Runnable solution:

 

Alternative titles

  1. JavaScript - how to empty object
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join