Three Techniques for Clearing an Array in JavaScript

Posted by

3 Ways to Empty an Array in JavaScript

3 Ways to Empty an Array in JavaScript

Emptying an array in JavaScript can be done in multiple ways, depending on the requirements and preferences of the developer. In this article, we will explore three different ways to empty an array in JavaScript.

Method 1: Using the length property

The simplest way to empty an array in JavaScript is by setting its length to 0. This method is straightforward and efficient, as it directly modifies the length of the array without iterating through each element.


var arr = [1, 2, 3, 4, 5];
arr.length = 0;
console.log(arr); // Output: []

Method 2: Using the splice() method

The splice() method is another approach to empty an array in JavaScript. It can be used to remove elements starting from a specified index. By using the splice() method and setting the start index to 0, we can effectively remove all elements from the array.


var arr = [1, 2, 3, 4, 5];
arr.splice(0, arr.length);
console.log(arr); // Output: []

Method 3: Reassigning an empty array

Another way to empty an array is by reassigning it to a new empty array. This method creates a new array instance, effectively removing all elements from the original array.


var arr = [1, 2, 3, 4, 5];
arr = [];
console.log(arr); // Output: []

These are three different ways to empty an array in JavaScript. Each method has its own advantages and can be used based on the specific requirements of the task at hand.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@ian.dalisay
8 months ago

Array#splice seems more concise than explicitly setting its length. It's more safer than the latter 2.