Table of Contents
Arrays in JavaScript are one of the most useful data structures in the language.
Arrays can be used to store any number of values, and they can be used to store any type of value.
To get started with using them, you'll want to create an empty array so that you can later on add elements to them.
In this post, we'll learn the three easiest ways to create an empty array in JavaScript.
Using the bracket syntax
The most common way to create an empty array is to use the bracket syntax.
Let's create an array called array using the bracket syntax:
JAVASCRIPTconst array = [];
You can confirm this is an array by using the .length property:
JAVASCRIPTconst array = [];
console.log(array.length);
BASH0
Using the Array constructor
Another way to create an empty array is to use the Array constructor.
This more explicit way of creating an array is useful when you want to create an array with a specific length.
Let's create an array called array using the Array constructor:
JAVASCRIPTconst array = new Array();
If you wanted to add values to it at the start, you can pass in the values as parameters:
JAVASCRIPTconst array = new Array(1, 2, 3, 4, 5);
console.log(array);
BASH[1, 2, 3, 4, 5]
Setting the length to 0
Another way to create an empty array is to set the length of an existing array to 0.
Let's first create an array with elements in them:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
Then, we can set the length of the array to 0:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
array.length = 0;
console.log(array);
BASH[]
The reason this works is because the length property is a setter as well as a getter, meaning that when you set it, it will automatically re-size the array to the new length.
Conclusion
In this post, we learned the three easiest ways to create an empty array in JavaScript.
You can either use the bracket syntax, use the Array constructor, or set the length of an existing array to 0.
Thanks for reading!
Managing PHP Dependencies with Composer
Getting Started with Electron
Git Tutorial: Learn how to use Version Control
How to Set Up Cron Jobs in Linux
How to deploy a .NET app using Docker
Best Visual Studio Code Extensions for 2022
How to deploy an Express app using Docker
How to deploy a Node app using Docker
How to Scrape the Web using Node.js and Puppeteer
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with Vuex: Managing State in Vue
Using Axios to Pull Data from a REST API
