Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
javascript
empty
communitycreator

How to empty an array in JavaScript

Chibueze Sam-Obisike

In this shot, we will learn how to empty an array in JavaScript.

An array is a single variable that stores several items.

Methods of emptying an array:

1. Setting the array

In this method, we initialize an array and populate it with variables to empty the array. We set the initialized array to an empty array type []. On console.log, we can see that the array becomes empty. This is arguably one of the fastest ways to empty an array.

Console
Emptying an array

2. Splice method

For JavaScript Array objects, the splice() function is a built-in method. It allows you to update the array’s content by deleting or replacing current items with new ones. This function alters the original array and returns a new array with the deleted elements.

Console
Emptying an array

The splice method removes all the elements from the initial array.

3. Setting the length of the array

We can explicitly set the length of the value of the array to be zero, which causes all other elements in the array to be empty.

Console
Emptying an array

RELATED TAGS

array
javascript
empty
communitycreator

CONTRIBUTOR

Chibueze Sam-Obisike
RELATED COURSES

View all Courses

Keep Exploring