How to Empty an Array in JavaScript
Table of Contents
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.
In this post, we'll look at all the ways to empty an array in JavaScript.
How to empty an array in JavaScript
Let's say you have this array:
JAVASCRIPTlet array = [1, 2, 3, 4, 5];
The easiest way to empty it out is to just re-assign it an empty array:
JAVASCRIPTlet array = [1, 2, 3, 4, 5];
array = [];
console.log(array);
JAVASCRIPT[]
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 0
.
JAVASCRIPTlet array = [1, 2, 3, 4, 5];
array.length = 0;
console.log(array);
BASH[]
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.
JAVASCRIPTlet array = [1, 2, 3, 4, 5];
const contents = array.splice(0, array.length);
console.log(array);
console.log(contents);
BASH[]
[1, 2, 3, 4, 5]
Conclusion
In this post, we learned at several ways to empty an array in JavaScript.
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!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript