Empty the Array with JavaScript | Plantpot

Empty the Array with JavaScript

Web Dev
Sponsored links

In this article, I will introduce how to empty the array with JavaScript.

Empty the array

Set the length to 0 to empty the array.

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

You can also assign an empty array.

let arr = [1,2,3];
arr = [];

Check if the array is empty

Also use length to check if the array is empty.

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

if(arr.length == 0) {
  // the array is empty
}

Since 0 represents false in JavaScript, you can also write it as follows.

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

if(!arr.length) {
  // the array is empty
}