Sometimes when you're working with an array, you'll want to empty it out, or clear it out.
Doing so allows you to not have to define a new variable, and then fill in your empty array with new elements in the future.
Let's say you have this array:
let array = [1, 2, 3, 4, 5];
The easiest way to empty it out is to just re-assign it an empty array:
let array = [1, 2, 3, 4, 5]; array = ; console.log(array);
This method works best when this array was not used as a reference for another array.
Another common way to empty out an array is to just update its length to
let array = [1, 2, 3, 4, 5]; array.length = 0; console.log(array);
The reason this method works is because when you update the length of an array, it will automatically re-size the array to the new length, meaning if you decrease the length, it will remove the elements from the end of the array.
Alternatively, if you want to clear out the array while also returning all of the cleared elements, you can just splice out the entire array using
slice() and passing in the first and last indexes as the parameters.
let array = [1, 2, 3, 4, 5]; const contents = array.splice(0, array.length); console.log(array); console.log(contents);
 [1, 2, 3, 4, 5]
You can either re-assign it to an empty array, or update its length to
0, or splice out the entire array.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!