Create empty array with JavaScript

Here are three ways to create an empty array using JavaScript

Posted on May 31, 2021

There are three ways you can create an empty array using JavaScript. This tutorial will help you to learn them all.

The first way is that you can get an empty array by assigning the array literal notation to a variable as follows:

let firstArr = [];
let secondArr = ["Nathan", "Jack"];

The square brackets symbol [] is a symbol that starts and ends an array data type, so you can use it to assign an empty array.

The firstArr variable above will create a new empty array, while the secondArr variable will create an array with two elements.

You can also use the new Array() constructor to create a new array object like in the code below:

let firstArr = new Array();
let secondArr = new Array("Nathan", "Jack");

Both the array literal notation and the array constructor produce the same thing.

Finally, you can also create an empty array by setting the length property of your array into 0.

The following code creates a new array with two elements, but because the length is set to 0 in the second line, the array becomes empty:

let users = ["Nathan", "Ariel"];
users.length = 0;
console.log(users); // []

And that’s how you can create an empty array using JavaScript 😉

Related articles:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more