Explain Codes LogoExplain Codes Logo

How do I empty an array in JavaScript?

javascript
array-clearing
performance-benchmark
browser-compatibility
Anton ShumikhinbyAnton Shumikhin·Oct 18, 2024
TLDR

Simply set the length property of the array to 0:

let myArray = ['a', 'b', 'c']; // Bye-bye, elements myArray.length = 0; // Now myArray is as empty as my fridge on Monday morning

You can also preserve references to the original array, by using the splice method:

myArray.splice(0, myArray.length); // myArray is now clean as a whistle, and references remain intact

Different Clearing Methods Explained

When you need to keep references

In JavaScript, you might have multiple references pointing to the same array. When you clear an array and still want to preserve these references, you should use:

let ref1 = myArray; let ref2 = myArray; // Even Black Widow can't delete those myArray.length = 0; console.log(ref1); // [] console.log(ref2); // [], Both references still point to the original, now empty, array

This works the same with the splice() method too:

myArray.splice(0, myArray.length);

When it's okay to break references

If it's not important for you to maintain the same array reference, re-assign an empty array. But remember, this kind of approach leaves previous references with the old array:

let ref1 = myArray; // New array, who dis? myArray = []; // ref1 is still living in the past and references the original array console.log(ref1); // ['a', 'b', 'c'] console.log(myArray); // []

Extraction of The Flash: Speed comparison

Different array clearing methods have different performance. To help you decide which one suits best for your code, here's a brief comparison:

  • length: 0 and splice() are quick as lightning and preserve references.
  • [] might have same speed, but creates a whole new array, making your previous references confused.
  • pop() inside a loop is like a snail on the racetrack - slow and doesn't always finish the job properly because of falsy values.

Element removal: The tortoise race

A while-loop with pop() does the job, but it's not as efficient:

// Pop, pop, pop, watching elements drop while (myArray.length) { myArray.pop(); // More pop than a Britney Spears concert }

Note the tricky part with this approach. This might prematurely brake the loop if an element is falsy:

// This loop can bail faster than a cat from a bath if an element is falsy while (myArray.pop()) {}

Emptied, not replaced

Now consider this scenario: a special train that can simply vaporize its passengers, while being the same train:

// Passengers vanish in thin air train.length = 0; // The original train 🚂 remains, now all shiny and clean from passengers.

A wish-list feature

We all know that JavaScript continues to evolve. In an ideal world, we would have a method like Array.clear(), but alas, we need to create our own:

// Maybe one day, JavaScript... Array.prototype.clear = function() { this.length = 0; }; myArray.clear(); // Just like in my dreams...

BenchPress for your Code

Performance can be a concern when running heavy-duty arrays. Use performance benchmark tools such as jsben.ch and see which method raids the CPU less. And remember, comparison between arrays using == will prove unsuccessful, as they aren't the same object.

Cross-browser compatibility and future-proofing

Evergreen In all browsers

The good news is both length: 0 and splice() have cross-browser compatibility:

// Works everywhere, like a roach in a nuclear winter myArray.length = 0; myArray.splice(0, myArray.length);

Choose your Cleaner

Think of clearing an array as deciding on a cleaning service for your room. It can be quick and thorough (length: 0), keeping the room intact yet sparkling. Or it can opt for complete makeover (A = []).

Factors affecting your choice

Select the best method for your array depending on:

  • Efficiency: How fast it needs to finish?
  • Referential integrity: Should other variables be enlightened with the emptied array?
  • Browser compatibility: Can it run even on your great-grandpa's browser?