Home / Snippets / How to Empty an Array in Javascript
How to Empty an Array in Javascript cover

How to Empty an Array in Javascript

99

2 years ago

0 comments

In this short snippet, you will learn How to Empty an Array in Javascript the easy way. Let's get started.

Method 1 - Using Array Splice

const array = [1, 2, 3, 4, 5];
array.splice(0);
console.log(array); // -> []
The splice(0) method will remove array from 0 to end

Method 2 - Length Trick

const array = [1, 2, 3, 4, 5];
array.length = 0;
console.log(array); // -> []

Extra Notes

If there is only one reference to the array, you may also want to assign a new array to the variable. The old array would be garbage collected.
let array = [1, 2, 3, 4, 5];
array = [];
However this will cause an issue if there are more than one reference to the same array.
let array = [1, 2, 3, 4, 5];
let array2 = array;
array = [];

console.log(array2); // -> [1, 2, 3, 4, 5];
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this