Ways to Empty an Array in JavaScript and the Consequences

Co-Founder, @CreoWis | Teacher, @tapaScript | Founder, @ReactPlay | YouTuber | Writer | Human
Search for a command to run...

Co-Founder, @CreoWis | Teacher, @tapaScript | Founder, @ReactPlay | YouTuber | Writer | Human
This is an awesome article. Thanks. There can be many ways to solve a problem, but knowing the consequences helps in using the right one and during debugging.
Traditional SSR is great, but it has a massive buffering problem. Let's look into the SSR Streaming and learn how it could be a game changer.

Learn how to build maintainable, reusable forms in React using design patterns like custom hooks, compound components, and context for scalable CRUD

Learn how JavaScript variables work, including let vs const, primitive and reference types, pass by value, and how JavaScript stores data in memory.

A beginner-friendly introduction to JavaScript covering what it is, how it works, and how to set up your JavaScript environment

Learn how the promises are handled internally using event loop. This concept is essentials to debug and work with async programming.

GreenRoots Blog - A Blog by Tapas Adhikary
186 posts
Educator | YouTuber | Building ReactPlay | Let's Connect
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,
consequences of being different for the same outcome?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!
The most simple way of doing it is like,
const arr = [ 1, 2, 3, 4, 5 ];
arr.length = 0;
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,
myArray and yourArray are empty now.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.
It is as simple as doing:
let arr = [ 1, 2, 3, 4, 5 ];
arr = [];
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,
hisArray is changed however the other array herArray is still unchanged.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.
Image Courtesy: https://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.
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 => []
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.
Do not use this approach if you have the option to use previous approaches when dealing with large arrays.
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']
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.
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.
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 []
It is slower and you may want to prefer the other approaches over this one.
In my day to day code reviews, I have seen the usage of Approach # 1 and 2 heavily for emptying the Array,
arr.length()splice() methodnew ArrayPlease 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.