Skip to content

How to empty object in JavaScript | Code

  • by

Use a loop to empty object in JavaScript. The loop will iterate over all the enumerable properties of the object and use the delete operator to delete each property in every iteration.

Empty object in JavaScript

Simple example code.

<!DOCTYPE html>
  <script >
    const obj = {1: 'one', 2: 'two'};

    for (const key in obj) {
      delete obj[key];



How to empty object in JavaScript

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

If object contains non-enumerable properties, then use the following approach to clear an object.

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)); // []

Removing all properties from an object

There are two possible solutions to the problem: Assign an empty object

req.session = {};

Delete properties one-by-one

Object.keys(object).forEach(key => delete object[key]);

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *