How to Clear an Object in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 11 20212 min read

banner

Photo by Abbat

Clear an Object in JavaScript #

To clear an object and delete all its properties use a for..in loop. The loop will iterate over all the enumerable properties of the object. In each iteration use the delete operator to delete each 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 enumerable properties.

An enumerable property is one that we added on the object using simple assignment, e.g. . or [] assignment.

Properties assigned on the object using the Object.definedProperty method are non-enumerable by default and 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 keyword 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 in our code as opposed to variables using the const keyword, which 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)); // []

In the code snippet we use the Object.getOwnPropertyNames method to get an array the enumerable and non-enumerable properties of the object.

We then use the Array.forEach method to iterate over all elements in the array and clear 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee