How to empty the contents in an array in JavaScript?

Published November 22, 2020

There are many ways to empty the contents in an array in JavaScript.

Using assignment operator =

One of the ways is to use the assignment operator = like this,

Consider this array of numbers,

// number array
let numbersArr = [23, 45, 56, 78];

Now let's emtpty the contents array using the assignment Operator =,

// number array
let numbersArr = [23, 45, 56, 78];

// empty contents in array
// using = operator
numbersArr = [];

console.log(numbersArr); // []

See this example live in JSBin.

But as you can see the assignment operator works only if the array is declared with the keyword let or var and doesn't work if declared const keyword.

Setting the length property to 0

To overcome the above problem, You can use set the length property of the array to 0 like this,

// number array
const numbersArr = [23, 45, 56, 78];

// empty contents in array
// by setting length property to 0
numbersArr.length = 0;

console.log(numbersArr); // []

See this example live in JSBin.

Using the splice() array method

Another way to empty the contents in an array is using the splice() array method like this,

// number array
const numbersArr = [23, 45, 56, 78];

// empty contents in array
// using the splice() array mehtod
numbersArr.splice(0, numbersArr.length);

console.log(numbersArr); // []

We have to pass the starting index as the first argument and the number of elements to delete from the starting index as the second argument, in our case 0 as the first argument and length of the array as the second argument.

See this example live in JSBin.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter