This page looks best with JavaScript enabled

Empty and reset objects in Javascript

 ·   ·  ☕ 2 min read

Is emptying objects akin to destroying them? Is destroying of objects easier than creating them? Let’s find out.

Initiate an object.

1
2
let apple = { name: "apple", color: "red" };
console.log("apple: ", apple); // { name: 'apple', color: 'red' }

Reset value

1
2
3
// the easy way to reset apple
apple = {};
console.log("apple: ", apple); // {}

The above piece of code will reset apple object.

Upon initiation memory was allocated to the defined object. Then, the variable apple was made to refer to the specific memory location where the object was stored.

By resetting the value of apple, you are creating a new memory location with an empty object and effectively pointing the variable apple to that location. The older memory has to be managed by the garbage collector.. Also, you will not be able to do this if you use const to declare apple.

For arrays: you could similarly do ..

1
2
3
4
let planets = ["mercury", "venus"];
planets = [];

// or planets.length = 0;

The consequences are same as that of an object.

Empty Responsibly

You could take things in your own hands, by demolishing the object in place and rebuilding it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let apple = { name: "apple", color: "red" };
console.log("apple: ", apple); // { name: 'apple', color: 'red' }

// what some say is the 'responsible' way
for (let prop in apple) {
  delete apple[prop];
}

console.log("apple: ", apple); // {}

apple["size"] = "small";
console.log("apple: ", apple); // { size: 'small' }

Empty Arrays

To empty arrays, you can do the following -

1
2
3
4
5
6
7
8
9
let planets = ["mercury", "venus", "earth"];

for (planet in planets) {
  planets.pop(planet);
}
if (planets.length == 1) planets.pop(planet);
// get the last element

console.log(planets); // []

Personally, I have been using the short hand notation and am super comfortable leaving the job of clearing memory to the garbage collector.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things