4 Ways to Empty an Array in Node.js

Originally published by Nick Major at https://coderrocketfuel.com

Introduction

There are various ways to empty an array of all it's contents. We'll show you each of the four ways in this article.

Let's get started!

Table of Contents

  1.  Create a New Empty Array
  2.  Set Length To Zero
  3.  Using Splice()
  4.  Loop Over & Remove Each Value

1. Create a New Empty Array

This method will create a brand new array and is the fastest method of the four because it doesn't change anything in the original array.

Here's the code:

let names = ["Johnny", "Billy", "Sandy"]
 
names = []
// []

You should be careful with this method because if you've referenced the original array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original value.

2. Set Length To Zero

This method uses the .length method to set the length of the array to zero.

This is the second-fastest method of the four.

Here's the code:

const names = ["Johnny", "Billy", "Sandy"]
 
names.length = 0
// []

3. Using Splice()

This method uses the splice() method to return the array with all the removed items.

Here's the code:

const names = ["Johnny", "Billy", "Sandy"]
 
names.splice(0, names.length)
// []

This method will return a copy of the original array. But it doesn't have much of an effect on performance.

4. Loop Over & Remove Each Value

This method will use a while loop to pop() each item in the array. This is both the slowest and least succinct method of the four.

Here's the code:

const names = ["Johnny", "Billy", "Sandy"]
 
while (names.length > 0) {
  names.pop()
}
// []

Conclusion

There you have it! These are four ways to empty an array in Node.js.

Did we miss any methods you know of? Let us know in the comments!

As always, thanks for reading!

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Best 50 Nodejs interview questions from Beginners to Advanced in 2019

Node.js 12: The future of server-side JavaScript

An Introduction to Node.js Design Patterns

Basic Server Side Rendering with Vue.js and Express

Fullstack Vue App with MongoDB, Express.js and Node.js

How to create a full stack React/Express/MongoDB app using Docker

#node-js #web-development #javascript

4 Ways to Empty an Array in Node.js
24.50 GEEK