How to empty an array in JavaScript?


There are a couple of ways to empty an array in javascript.

Let's suppose take an array

var array1 = [1,2,3,4,5,6,7];

Method 1

var array1 = [];

The code above will set the number array to a new empty array. This is recommended when you don't have any references to the original array 'array1'. You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged.

Example

<html>
<body>
<script>
   var array1 = [1,2,3,4,5,6,7];  // Created array
   var anotherArray = array1;     // Referenced array1 by another variable
   array1 = [];                   // Empty the array
   document.write(anotherArray);  // Output [1,2,3,4,5,6,7]
</script>
</body>
</html>

Method 2

var array1.length = 0;

The line of code above will make the length of original array to 0 there by emptying the array.

Example

<html>
<body>
<script>
   var array1 = [1,2,3,4,5,6,7]; // Created array
   var anotherArray = array1; // Referenced array1 by another variable
   array1.length = 0; // Empty the array by setting length to 0
   console.log(anotherArray); // Output []
</script>
</body>
</html>

Method 3

array1.splice(0, array1.length);

The above line of code also works perfectly. This way of code will update all the references of the original array.

Example

<html>
<body>
<script>
   var array1 = [1,2,3,4,5,6,7]; // Created array
   var anotherArray = array1; // Referenced array1 by another variable
   array1.splice(0, array1.length); // Empty the array by setting length to 0
   console.log(anotherArray); // Output []
</script>
</body>
</html>

Updated on: 30-Jul-2019

676 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements