How to Remove All Items from Array in Javascript

In this tutorial, you will learn how to remove all items from an array in javascript. As you already know, there are numerous built-in methods for arrays to add or remove items.  Emptying an array is pretty much like emptying a box full of items.
There are numerous ways to delete all items in an array. Some of them involve looping through an array and removing each item one by one, but I will show you one efficient way to accomplish this with one line of code.
In the following example, we are displaying all items in an array as well as the length of the array and upon click of a button, we are removing all items from the array which in turn will display nothing on the webpage and the length will become 0. Please have a look over the code example and steps given below.
  • We have a global variable users and it holds an array of strings as well as null or undefined elements.
  • We have the addUsers() method which is responsible for populating our ul element.
  • In addUsers() method, we are simply looping through the users array and creating a template string with a bunch of li elements.
  • We are displaying that list in the ul element and its length in the h1 element.
  • We have selected a button using the document.querySelector() method and stored it in btnRemove variable.
  • We have attached the click event listener to the button element.
  • In the event handler function, we are simply assigning an empty array ([]) to users variable and calling addUsers() method to update the output on the screen.
  • Since the array is empty, there will be no list items and the length will become 0.
let users = ['Peter', 'Marks', 'James', 'Mary', 'Ronald'];

function addUsers(){
    let template = => `<li>${user}</li>`).join('\n');
    document.querySelector('ul').innerHTML = template;


let btnRemove = document.querySelector('button');

btnRemove.addEventListener('click', () => {
    users = [];