In this post, we are going to learn How to empty an array in JavaScript. We will learn to use the array.length,array,splice(),assign an array to new array, by using array.pop() methods.
1. Assign array to new empty array
The fastest way to empty an array is to assign an array to an empty array. We have to make sure the other array should not reference to this array. Because it does not make changes to the referenced array.
In the below example, array2 referencing myarray. So setting myarray=[] remove all contents of the myarray but does not make a change in its reference array2.
JS Program Example
let myarray = [12,'jack',9,6,'rack'];
console.log(myarray)
let array2 = myarray;
myarray = [];
console.log('myarray:',myarray)
console.log('array2:',array2)
Output
[ 12, 'jack', 9, 6, 'rack' ]
myarray: []
array2: [ 12, 'jack', 9, 6, 'rack' ]
2. array.length=0 to empty array in JavaScript
We have an array with some elements as shown below. We have assigned an array. length = 0 to remove all elements and empty an array in JavaScript.The array. length property can be used in strict mode in ECMAScript 5.
Array. length also changes the reference array. In the below example array2 referencing myarray. So Setting myarray.length =0 also empty out the array2.
JS Program Example
let myarray = [12,'jack',9,6,'rack'];
let array2 = myarray ;
console.log(myarray )
myarray.length = 0;
console.log('myarray:',myarray)
console.log('array2:',array2
Output
[ 12, 'jack', 9, 6, 'rack' ]
myarray :[]
array2 :[]
3. Array.slice() to empty array in JavaScript
The array.splice() method changes the contents of an array by replacing or removing the element of the array.
Syntax
splice(start, deleteCount)
Parameters
- start : The first arguments is start index at which start deleting or replacing elements.
- deleteCount: Second argument how many elements to delete or replace. here is array.length
In the below example, we are removing all elements of the myarray to empty it.
JS Program Example
let myarray = [12,'jack',9,6,'rack'];
console.log(myarray )
myarray.splice(0,myarray .length);
console.log(myarray)
Output
[ 12, 'jack', 9, 6, 'rack' ]
[]
4. Array.pop() to empty array in JavaScript
The array.pop() method deletes the last element of the array and returns deleted element and changes the length of the array. We can use the pop() method with a while loop and remove an element one by one.
JS Program Example
let myarray = [12,'jack',9,6,'rack'];
console.log(myarray .pop())
console.log(myarray )
while(myarray .length > 0) {
myarray.pop()
}
console.log(myarray);
Output
[ 12, 'jack', 9, 6, 'rack' ]
[]
Summary
In this post, we have learned how to empty an array in javascript by using these ways
- assign an array to new array
- array.length
- array,splice()
- Using array.pop()