Clear Javascript Arrays in 3 ways

The first way to clear an array is to assign an empty array to the variable:

  
  
let myArray = [1,2,3,4];
myArray = [];

console.log(myArray);
  

The second way is by using Array.prototype.pop() which removes the last element from an array and returns that element.

  
  
const myArray = [1,2,3,4];

myArray.forEach(() => {
  myArray.pop();
});

console.log(myArray);
  

The third way to clear an array is by simply setting the length of the array to 0.

  
  
let myArray = [1,2,3,4];
myArray.length = 0;

console.log(myArray);
  

Andy

Front-end Engineer & Designer based in Dublin currently working @IBM.
I write about: Javascript, HTML, CSS, React JS, React Native and UI/UX Design.

Add comment