How to empty an array in JavaScript

In this tutorial, we’ll be looking at the different ways to empty an array in JavaScript. We’ll look at manipulating the length, assigning empty arrays to the original array, using various other pre-defined array methods, and looping through the array.

Set the array’s length to 0

One of the easiest ways to reset an array is by setting its length to 0. The ‘length’ property not only displays the current length of an array but can also be used to reduce or increase the length as we see fit.

For example, if we set the length of the array [1,2,3] to 5, we’ve artificially increased its length, and the 2 remaining slots will be filled with undefined, like this: [1,2,3,undefined,undefined].

For our current purpose though, we’ll just be setting the length to 0. This will remove any current elements in the array, and we’ll end up with an empty array, as shown in the example below:

let arr = ['Apple','Orange','Grapes'];

arr.length = 0;

console.log(`Array is '${arr}'`); //Array is '' 

Assign an empty array to the original array

Apart from setting an array’s length, we can also assign an empty array to it to reset it. There are different ways of creating and assigning an empty array, and let’s look at all of them in this section.

The easiest way of creating an empty array

The easiest way of creating an empty array is by using []. Two empty square brackets with nothing inside it indicates an empty array. Assign this to the array you want to empty, and you’re good to go.

arr = []; 

Alternatively, you can use the new Array() syntax to achieve the same result.

arr = new Array(); 

Use the Array.of method to create an empty array

You can also use the Array.of() method to create an empty array. This method was designed to return a new array from the set of arguments you’ve sent to it, but if you send no arguments, it’ll return an empty array.

arr = Array.of(); 

This is not the most economical method, compared to just creating and assigning an empty array to your variable, but I want to give you all the options you have at hand, so you can pick and choose the one that suits your purposes.

Use the Array.from method

You can also use the Array.from() method. Array.from forms an array from a string or an object. For example, if you send ‘ABC’ as the argument, you’ll get back the array [‘A’,’B’,’C’].

So, in a roundabout manner, you can send an empty string or an empty object to this method and get back an empty array as well, as shown below:

arr = Array.from(''); 
]arr = Array.from({}); 

You can also send random numbers as the arguments and get back an empty array since this method is incompatible with numbers.

arr = Array.from(012); 

Use pre-defined Array methods

JavaScript comes with a host of pre-defined Array methods that can be used to manipulate arrays in numerous ways, and we can use some of these methods to empty our arrays as well.

Let’s look at them in this section.

Using the splice() method

The splice method is originally used to remove element(s) and replace them with new elements, but by changing the values you send during the function call, you can make it remove the entire array and replace it with nothing.

The first argument indicates the first position of the removal. Make this 0, so the removal starts from the first element of the array.

The second argument indicates the number of elements you want removed. Make this array.length, indicating that you want to remove all the elements from the array.

Finally, from the 3rd argument, you’ll be expected to send the values you want the removed elements replaced with.

We’re going to leave this empty, indicating that we don’t want to replace the removed elements with anything, as shown below:

arr.splice(0,arr.length); 

Using the filter method

There’s also the filter method. As the name implies, this method is used to filter out an array based on a given condition.

It iterates through every element of the original array and creates a new array with only the elements that fulfilled the condition (returned true for the condition).

All we must do here is return false for every single iteration. This will return an empty array since no element fulfilled the condition (always returned false).

Then, we can assign this empty array back to the original array, effectively emptying it, as shown in the code snippet below:

arr = arr.filter(() => { return false }); 

Using the reduce method

The reduce method works like the filter method in that it iterates through all the elements of a given array. But that’s where the similarities stop.

While the filter method filters through an array and returns a new array with the selected elements, the reduce methods contains a reducer function that does calculations on every element and returns a cumulative result at the end.

We’re going to change things now though. We’re going to return an empty array for every single iteration. This means, at the end, the reduce function will return an empty array, which can be reassigned to the original array, as shown below:

arr = arr.reduce(() => []); 

Using the fill method

There’s also the ’fill’ method. As you know, once you create an array of a certain size, we can use the ‘fill’ method to fill it with a certain value.

In our case, our original array already has elements, so it is of a certain size.

If we use the fill method to fill this array with ‘undefined’, or ‘null’ values, we’ve technically emptied our array of any values, though it can’t be considered an empty array as such, as shown below:

arr.fill(undefined); //can be 'null' too – result: ',,' 

So, this is more of an alternative method to emptying an array. Use this method with discretion.

Looping through the array

So far, we’ve looked at shortcuts, or methods that take barely a single line of code. Let’s look at manual methods now.

I’m talking about looping through the array and removing every single element during every iteration of the loop.

For loop and pop

One of the easiest ways to loop through a loop is by using the ‘for’ loop. To start with, find the length of the array by using the ‘length’ property.

We’re going to assign this value to a separate variable and use this in our ‘for’ loop, so when we use the ‘pop’ method and our arrray’s length changes, it doesn’t affect the number of iterations our loop makes.

Then, create a ‘for’ loop that loops from 0 (the 1st index of any array) through length – 1 (loops ‘length’ number of times, or throughout the entire array).

For every iteration of the loop, use the pop() method to pop the last element of the array.

So, for the first iteration, the last element will be removed, for the second iteration, the second last element will be removed, and so on.

let arr = ['Apple','Orange','Grapes'];

const length = arr.length; 

for(let i = 0; i < length; i++) {
    arr.pop();
}

console.log(`Array is '${arr}'`); //Array is '' 

You can use ‘while’ loop instead as well.

For in and delete

For this example, let’s use the ‘for in’ loop and the delete keyword. You can go ahead and mix up your loops and methods. For instance, use the ‘for’ loop with the ‘delete’ keyword, if you’d like.

The ‘for in’ loop iterates through an array, and for every iteration, you get the current element’s index (i), which can be used in your code’s logic.

In our case, we’re going to use ‘i’ to delete arr[i], that is, the element in the ith position, as shown in the code block below:

let arr = ['Apple','Orange','Grapes'];

for(let i in arr) {
    delete arr[i];
}

console.log(`Array is '${arr}'`); //Array is ',,' 

There’s a problem with this method though.

You’ll be left with holes in the array, that is, undefined values that you’ll need to fill (just like when we used the ‘fill’ method, so be careful while using the ‘delete’ keyword to remove array elements.

While loop and shift

You can also use the ‘shift’ method while iterating through an array. The shift() method works like the pop(), where the only difference is that ‘shift’ removes the first element of an array while ‘pop’ removes the last element.

In this example, let’s use the ‘while’ loop, and keep it iterating till the array’s length becomes 0 (all the elements have been removed/shifted).

For every iteration of the loop, let’s use the ‘shift’ method on the array to remove the current first element, as shown below:

while(arr.length > 0) {
    arr.shift();
} 

That’s it! We’ve looked at 4 different major ways of emptying an array in JavaScript, from assigning it a length of 0, assigning it an empty array, using various pre-defined Array methods, and looping through the array and removing every element.

Leave a Comment