In Javascript how to empty an array


There are multiple ways to clear/empty an array in JavaScript. You need to use them based on the context. Let us look at each of them. Assume we have an array defined as −

let arr = [1, 'test', {}, 123.43];

Substituting with a new array −

arr = [];

This is the fastest way. This will set arr to a new array. This is perfect if you don't have any references from other places to the original arr. If you do, those references won't be updated and those places will continue to use the old array.

Setting length prop to 0 −

arr.length = 0

This will clear the existing array by setting its length to 0. Fast solution, but this won't free up the objects in this array and may have some memory implications. In order to clean objects in array from memory, they need to be explicitly removed.

Splice the whole array

arr.splice(0, arr.length)

This will remove all elements from the array and will actually clean the original array.

Updated on: 07-Oct-2023

22K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements