How to Empty an Array in JavaScript?

How to Empty an Array in JavaScript?

Ferenc Almasi β€’ Last updated 2020 November 01 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

There are a number of ways to empty an array in JavaScript, probably the simplest is to reassign the variable to an empty array:

Copied to clipboard!
let array = [1, 2, 3];

// Assigning to an empty array
array = [];
reassignment.js

You can also set the length of the array to 0:

Copied to clipboard!
// Setting its length property to 0
array.length = 0;
length.js

Splice can be also used get rid of everything from an array:

Copied to clipboard!
// Using splice with the array's length
array.splice(0, array.length);
splice.js

So which one to use? The simplest, and also the fastest operation is simply reassigning the variable to an empty array. To see the performance difference, checkout the 3 solutions on JSBen.

How you can empty an array in JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.