How to Create an Empty Array in JavaScript

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:
const array = [];
You can confirm this is an array by using the .length
property:
const array = [];
console.log(array.length);
0
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:
const array = new Array();
If you wanted to add values to it at the start, you can pass in the values as parameters:
const array = new Array(1, 2, 3, 4, 5);
console.log(array);
[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:
const array = [1, 2, 3, 4, 5];
Then, we can set the length of the array to 0
:
const array = [1, 2, 3, 4, 5];
array.length = 0;
console.log(array);
[]
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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!