How to empty an array in JavaScript

How to empty an array in JavaScript
December 22, 2022

Arrays are collections of data. Javascript arrays can be initialized with various data types such as strings, numbers, or objects.

There are several ways to empty an array in JavaScript. Here are 5 ways to empty an array:

1. Assign an empty array to the original array:

let myArray = [1, 2, 3, 4, 5];
myArray = []; //assigning an empty array

This will replace the original array with a new, empty array.

2. Set the length property to 0:

let myArray = [1, 2, 3, 4, 5];
myArray.length = 0; //setting length property

This will remove all elements from the array, leaving it empty.

3. Use the splice() method:

let myArray = [1, 2, 3, 4, 5];
myArray.splice(0, myArray.length); //splice method to remove elements


This will remove all elements from the array by using the splice() method to remove a range of elements from the array.

4. Use the fill() method:

let myArray = [1, 2, 3, 4, 5];
myArray.fill(0);

This will fill the entire array with a single value (in this case, 0). You can then use the splice() method or the length property to remove the elements, as described above.

5. Use loop and pop()

var myArray = [1, 2, 3, 4, 5];

for(var i = myArray.length; i >= 0; i--)
{
     myArray.pop(); //pop method to remove array elements one by one
}

console.log(myArray);

You can use the pop() method to remove elements from the end of an array one at a time until the array is empty.


Any of these methods will effectively empty the array in JavaScript.

Do you want all Front-End Interview Questions and Answers?

Click here to get the Front-End Developer Interview Kit and get started this weekend to prepare for your dream job(Special Offer)


Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Are you looking for Front-end Developer Job?

Get Front-end Interview Kit Now, And Be Prepared to Get Your Dream Job

Get Front-end Interview Kit

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates