Ways to Empty an Array in JavaScript and the Consequences

Ways to Empty an Array in JavaScript and the Consequences

As it is famously quoted,

The only way you can stay on top is to remember to touch the bottom and get back to basics.

Here is one topic from JavaScript's basic concepts. It is about, Ways to Empty an Array. But wait, is that all? No, there is more to it,

  • Why are we even discussing it here?
  • There seem to be multiple ways, so how are they different?
  • What are the consequences of being different for the same outcome?
  • Well, it may help in an interview as well. 😃

I believe, we need to know a bit more than just the ways of achieving it. It is important to know the stories behind the approaches to appreciate possible outcomes and abuses. Please keep reading!

Approach 1: Simple, arr.length = 0

The most simple way of doing it is like,

const arr = [ 1, 2, 3, 4, 5 ];
arr.length = 0;

Consequences

This approach mutates the original array reference. It means if you assign one array reference to another with assignment operator(=), applying this approach on one array will clean the other one too.

Remember, Arrays are non-primitive. If we assign a non-Primitive value to a variable, that variable doesn't actually hold the value, rather holds the reference. Let us understand it better with an example:

let myArray = ['My', 'Array'];

let yourArray = ['Some', 'thing'];

yourArray = myArray;

console.time('Approach 1: arr.length = 0');
myArray.length = 0;
console.timeEnd('Approach 1: arr.length = 0');

console.group('Approach 1: Empty array using arr.length property of the Array')
console.log('myArray =>', myArray);
console.log('yourArray =>', yourArray);
console.groupEnd();

I am doing little more than expected here. I am also calculating the time(in milliseconds) taken to empty the array. Please note, I shall be doing the same for all the approaches so that, we get an idea of the performance as well.

Coming back to the output,

Approach  1: arr.length = 0: 0.013 ms
Approach  1: Empty array using arr.length property of the Array
  myArray => []
  yourArray => []

It says,

  • This approach took 0.013 ms.
  • As we see, both myArray and yourArray are empty now.

Learning

In a situation like the above, when you empty one of the arrays using arr.length = 0, both references will now point to the same empty array.

Hence the learning is, don’t use this technique if you are unsure about how the arrays are referenced and related in the code. You may end up clearing an array unknowingly and face production issues. In case, you are sure about it, this approach works really well.

Approach 2: Assign a reference to a New array

It is as simple as doing:

let arr = [ 1, 2, 3, 4, 5 ];
arr = [];

Consequences

This approach doesn't mutate the original array reference. It assigns the reference to an empty array to the original variable. Let us understand this by an example:

let hisArray = [ 'His', 'Array' ];

let herArray = [ 'Her', 'Array'];

herArray = hisArray;

console.time('Approach  2: new assignment');
hisArray = [];
console.timeEnd('Approach  2: new assignment');

console.group('Approach  2: Empty array by assigning a new empty Array []')
console.log('hisArray =>', hisArray);
console.log('herArray =>', herArray);
console.groupEnd();

The output,

Approach  2: new assignment: 0.003 ms
Approach  2: Empty array by assigning a new empty Array []
  hisArray => []
  herArray => [ 'His', 'Array' ]

As you notice,

  • This approach took lesser time than the previous one, i.e, just 0.003 ms
  • The Original array hisArray is changed however the other array herArray is still unchanged.

Learning

This approach is suitable only if you don't have references to the original array. You should be careful with this approach when having references to the array. As the original array will remain unchanged, this may lead to a Memory Leak.

Hence the learning is, use this approach if you only reference the array by its original variable.

BREAK TIME

matt-hoffman-310320-unsplash.jpg Image Courtesy: unsplash.com

I have used the term reference a few times. It is really important to understand the concept of reference and value for primitive and non-Primitive types.

In case you need, please have a look into this,

Alright, let us continue discussing the other approaches.

Approach 3: Use pop() till the end

Another approach is to use the pop() method of the array to remove an element. So what to do when want to remove all the elements? Yes! use pop() in a loop,

let someArray = [ 'Some', 'Array'];

console.time('Approach  3: pop()');
while(someArray.length > 0) {
    someArray.pop();
}
console.timeEnd('Approach  3: pop()');

console.group('Approach  3: Use pop until death');
console.log('someArray => ', someArray);
console.groupEnd();

The output is,

Approach  3: pop(): 0.016 ms
Approach  3: Use pop until death
  someArray => []

Consequences

This approach can get things very slow as the number of elements in the array grows. You may find performance differences between this approach and previous approaches with a higher number of elements in the array.

Learning

Do not use this approach if you have the option to use previous approaches when dealing with large arrays.

Approach 4: Use splice()

You can use the splice method on the array to empty it. It is as convenient as Approach 1 and 2. But, it comes with a hidden cost!

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

let names = ['tom', 'jerry'];

console.time('Approach  4: splice()');
let spliced = names.splice(0, names.length);
console.timeEnd('Approach  4: splice()');

console.group('Approach  4: Use splice!');
console.log('names => ', names);
console.log('spliced => ', spliced )
console.groupEnd();

Give a close look into the output here:

Approach  4: splice(): 0.016 ms
Approach  4: Use splice!
  names =>  []
  spliced =>  ['tom', 'jerry']

Consequences

Using .splice() works perfectly and the performance is also good! But since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array.

Learning

Do not use this approach if you do not have to take the overhead of the returned copy of the original array. Otherwise, you can use splice() to remove one or more elements easily.

Approach 5: How about Shift()?

Here is the last approach, using the shift() method. What does shift() do?

The shift() method removes the first element from an array and returns that removed element.

Have a look into the code below:

let againNames = ['tom', 'jerry'];

console.time('Approach  5: shift()');
while (againNames.length > 0) {
    againNames.shift();
}
console.timeEnd('Approach  5: shift()');

console.group('Approach  5: How about Shift()?');
console.log('againNames', againNames);
console.groupEnd();

... and the output:

Approach  5: shift(): 0.018 ms
Approach  5: How about Shift()?
  againNames []

Consequences/Learning

It is slower and you may want to prefer the other approaches over this one.

Conclusion

In my day to day code reviews, I have seen the usage of Approach # 1 and 2 heavily for emptying the Array,

  • Usage of arr.length()
  • The splice() method
  • Assigning new Array

Please note, removing specific elements from an array and removing all elements are different use-cases. Please consider the approaches based on the use-cases.

Each of these approaches has its own consequences(advantages and disadvantages) and scope/time to use. The performance is another key in determining the approach for your implementation.

If you are interested to try out these approaches with different array structures, use this live benchmark site to do it.


There is a popular saying by Francis Bacon,

“Knowledge is power.”

I dare to extend it as,

Sharing is empowering.

If this article was useful, please share it so others can read it as well. You can @ me on Twitter (@tapasadhikary) with comments, or feel free to follow me.

Did you find this article valuable?

Support Tapas Adhikary by becoming a sponsor. Any amount is appreciated!