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 Solid
- Getting Started with Svelte
- Getting Started with Electron
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue