How to Clear an Object in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Clear an Object in JavaScript #

Use a for..in loop to clear an object and delete all its properties. The loop will iterate over all the enumerable properties in the object. On each iteration, use the delete operator to delete the current property.

index.js
const obj = {a: 'one', b: 'two'}; for (const key in obj) { delete obj[key]; } console.log(obj); // 👉️ {}

The for...in loop iterates over all of an object's enumerable properties.

An enumerable property is one that is added to the object using simple assignment, e.g. dot . or square brackets [] assignment.

Properties assigned to the object using the Object.definedProperty method are non-enumerable by default and are not iterated over in a for...in loop.

The Object.defineProperty method is mostly used by 3rd party library creators and not in day-to-day code, so chances are the for...in loop covers all of your object's properties.

It is much more performant to reassign the variable containing the object, setting it to an empty object. This is only possible if you used the let or var keywords to declare the object.
index.js
let obj = {a: 'one', b: 'two'}; obj = {}; console.log(obj); // 👉️ {}

Notice that we used the let keyword when declaring the obj variable.

The let keyword allows us to reassign the variable. Note that variables declared using const cannot be reassigned.

In the extremely unlikely scenario that your object contains non-enumerable properties, you can use the following approach to clear an object.

index.js
let obj = {a: 'one', b: 'two'}; Object.defineProperty(obj, 'color', { value: 'red', enumerable: false, // 👈️ defaults to false configurable: true, }); const allProperties = Object.getOwnPropertyNames(obj); console.log(allProperties); // 👉️ ['a', 'b', 'color'] allProperties.forEach(property => { delete obj[property]; }); console.log(Object.getOwnPropertyNames(obj)); // []

We used the Object.getOwnPropertyNames method to get an array of the enumerable and non-enumerable properties of the object.

We used the Array.forEach method to iterate over the array and cleared each property using the delete operator.

As previously mentioned, it's best to use the let keyword and reassign the variable to an empty object. This is the fastest way to clear the object and let the garbage collector do its job.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.