July 7, 2020
How to Remove All Items from Array in Javascript
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.
HTML & CSS
- 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 ourul
element. - In
addUsers()
method, we are simply looping through theusers
array and creating a template string with a bunch ofli
elements. - We are displaying that list in the
ul
element and its length in theh1
element. - We have selected a
button
using thedocument.querySelector()
method and stored it inbtnRemove
variable. - We have attached the
click
event listener to thebutton
element. - In the event handler function, we are simply assigning an empty array (
[]
) tousers
variable and callingaddUsers()
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 = users.map(user => `<li>${user}</li>`).join('\n'); document.querySelector('ul').innerHTML = template; } addUsers(); let btnRemove = document.querySelector('button'); btnRemove.addEventListener('click', () => { users = []; addUsers(); });
div
,button
,h1
, andul
). Thediv
element is just a wrapper for the rest of the elements.button
element is“Remove”
and for theh1
element is“Length”
.ul
element is empty for now since we will populate it dynamically using javascript.style.css
stylesheet inside thehead
element.script.js
with ascript
tag at the bottom.Javascript