Languages
[Edit]
EN

JavaScript - how to clear object

3 points
Created by:
Dirask Community
3960

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

Below examples show two solutions on how to do that:

  1. Assigning the object to a new empty object ({}),
  2. Using for loop to delete the object's properties.

Solution 1

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

Runnable solution:

// ONLINE-RUNNER:browser;

var user = {
  id: 1,
  name: 'John',
  age: 43
};

user = {};

console.log(JSON.stringify(user, null, 4)); // {}

Note: 
If we want to use this approach, the object cannot be const.

Solution 2

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

Runnable solution:

// ONLINE-RUNNER:browser;

const user = {
  id: 1,
  name: 'John',
  age: 43
};

for (var prop in user) {
	if (user.hasOwnProperty(prop)) {
		delete user[prop];
	}
}

console.log(JSON.stringify(user, null, 4)); // {}

Note:
This approach is slow when we're dealing with large objects.

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