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
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

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.