How to Empty an Array in JavaScript

There are various ways to empty an Array in JavaScript.
The easiest one is to set its length to 0:
let strArray = ["A", "B", "C","D", "E"];
strArray.length = 0;
Another method mutates the original array reference, assigning an empty array to the original variable:
var intArray = [1,2,3,4,5,6,7]
intArray = [];

Complete Example

var strArray = ["A", "B", "C","D", "E"];

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

function emptyArray(){
    
    console.log(" Before empty an array : " + strArray);
    strArray.length = 0;
    console.log(" After empty an array : " + strArray);

    console.log(" Before empty an array : " + intArray);
    intArray = [];
    console.log(" After empty an array : " + intArray);
}

emptyArray();
Output:
Before empty an array : A,B,C,D,E
After empty an array : 
Before empty an array : 1,2,3,4,5,6,7
After empty an array : 
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.
You can refer below screenshot for your testing:

Comments