Node.js — How to Reset and Empty an Array

When emptying an array in JavaScript/Node.js you’ll surely think of reassigning your array’s value to a new array. There’s another way to reset an array: set the length to zero. Let’s have a look at both ways.

Node.js Series Overview

Assign an Empty Array

A common way to reset an array is assigning an empty array:

let items = [ 'item1', 'item2', 'item3' ]  
items = []

// -> output: 0

This comes with the downside of creating a new array and leaving the old one for the garbage collector. Garbage collection is an optimized process in nowadays Node.js runtimes. It won’t create much headache for you as a developer.

Using a new array will not affect any value that references your array. Depending on where this array comes from this is safe to use because you’re not changing the values themselves.

Set the Array Length to Zero

Setting the length to zero will empty the existing array. It will also empty all participants.

let items = [ 'item1', 'item2', 'item3' ]  
items.length = 0

// -> output: 0

Using this approach, you don’t leave work for the garbage collector, but possibly affect referenced arrays and reset them as well. All JavaScript runtimes (Browser, Node.js) are optimized for the operation to set the array length to zero. There’s no performance penalty going this way.

Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.