Originally published by Nick Major at https://coderrocketfuel.com
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
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.
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 // []
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.
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() } // []
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
☞ 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