Clear Javascript Array

Clearing Javascript arrays is a common need. Assigning to an empty array=[] creates a new object, breaks all existing references, and often results in code breakage. This post shows a simple and effective solution for creating a removeAll() method without impacting existing references and array iterators.

Assigning Array.prototype.removeAll to a function is not safe because it defines the new function as enumerable and injects a new (function) object into the loop for (var p in this) {}; this is one reason not to use a generic property iterator when the intention is to iterate over the array’s elements.

In July of 2010 JavaScript 1.8.5 introduced Object.defineProperty. In addition to enabling the definition of a getter and setter methods that look like properties, this addition enables defining properties which are not enumerable.

The simple solution leveraging defineProperty is illustrated below. Use Object.defineProperty() to point the getter of Array.prototype.removeAll to a function which removes the array’s elements one at a time.

For older browsers which do not implement Object.defineProperty we still need to perform the assignment directly. Careful however, because such a direct assignment will break all legacy code performing general for (i in array) loops as it will iterate over the newly added function elements as well.

To see an example how this can be used to achieve polymorphism, e.g., across Arrays and Knockout ObservableArrays, see this post.

Safely Clearing Arrays

var removeAll_prototype = function () { while (this.length > 0) this.pop(); };
if (Object.defineProperty)
Object.defineProperty(Array.prototype, 'removeAll', {
enumerable:false, // this is the default value
value: removeAll_prototype // this is the function defined above
});
else
Array.prototype.removeAll = removeAll_prototype

That’s it!

Leave a comment

Who's the Coach?

Ben Ruiz Oatts is the insightful mastermind behind this coaching platform. Focused on personal and professional development, Ben offers fantastic coaching programs that bring experience and expertise to life.

Get weekly insights

We know that life's challenges are unique and complex for everyone. Coaching is here to help you find yourself and realize your full potential.

We know that life's challenges are unique and complex for everyone. Coaching is here to help you find yourself and realize your full potential.