In this tutorial we will see how to Empty an Array in JavaScript. JavaScript length property, array assignment, pop() method and splice() method can be used to remove all elements of array in JavaScript.
Table of Contents
JavaScript length property
The JavaScript length property sets or returns the number of elements in the array.
We can use length property to remove all elements of an array.
Take a look at the code given below.
<script>
const lang = ['HTML','CSS','JavaScript','PHP'];
lang.length = 0;
document.write('Array: ' + lang);
</script>
JavaScript Array Assignment
JavaScript Array Assignment is the simplest way to empty an array and remove it's all elements.
In this method we will assign our array to a new array, take a look at the code given below.
<script>
var lang = ['HTML','CSS','JavaScript','PHP'];
lang = [];
document.write('Array: ' + lang);
</script>
JavaScript pop() Method
The JavaScript pop() method removes the last element of the array.
We can use pop() method to remove all elements of array one by one. For this we will use JavaScript for loop and inside this for loop we will use pop() method.
In this example For loop will run equal to the length of the array and on each iteration last element of the array will be removed. This will remove all elements of array.
<script>
var lang = ['HTML','CSS','JavaScript','PHP'];
var x =lang.length;
for(a=0;a<x;a++)
{
lang.pop();
}
document.write(lang);
</script>
We can do same thing with the help of while loop as well, look at the code given below.
<script>
var lang = ['HTML','CSS','JavaScript','PHP'];
var x =lang.length;
while(x>0)
{
lang.pop();
}
document.write(lang);
</script>
JavaScript splice() Method
The JavaScript splice() method removes or replaces the elements of array. It is used to change the array.
We can use the splice() method to empty an array completely.
<script>
var lang = ['HTML','CSS','JavaScript','PHP'];
var x =lang.length;
lang.splice(0,x);
document.write(lang);
</script>
In this example 0 is the position from where it should remove elements of array, while x is number of elements to be removed, which is set equal to the length of the array.
Demo
Video Tutorial
Watch our video tutorial on how to Empty an Array in JavaScript.