We can use JavaScript to create an empty array easily by initializing the array to no items with open and closed square brackets.

var emptyArray = [];

In JavaScript, arrays are a collection of objects which are ordered. When working with arrays, it can be useful to be able to easily create an empty array, or an array with no items.

To create an empty array in JavaScript, you can initialize an array with no items with open and closed square brackets.

Below is a simple example showing how to create an empty array in JavaScript.

var emptyArray = [];

Properties of Empty Arrays in JavaScript

There are a few properties that empty arrays have in JavaScript.

First, empty arrays have length 0 and therefore are equal to False when converted to a boolean value.

Empty arrays have all of the methods available to them like regular arrays and typically you might initialize an empty array and then add items one by one as shown in the following code.

var someArray = [];

someArray.push(1);
someArray.push(2);
someArray.push(3);

console.log(someArray);

#Output:
[1, 2, 3]

How to Check if an Array is Empty in JavaScript

If you want to check if an array is empty in JavaScript, you just need to check for certain conditions.

We can easily check if an array is empty in JavaScript. An empty array has length 0, and is equal to False, so to check if an array is empty, we can just check one of these conditions.

Below are two ways you can check if an array is an empty array in JavaScript.

var emptyArray = [];

#length check
if ( emptyArray.length == 0){
  console.log("Array is empty!");
}

#if statement check
if (!emptyArray.length) {
  console.log("Array is empty!");
}

Hopefully this article has been useful for you to learn how to use JavaScript to create an empty array.

Categorized in:

JavaScript,

Last Update: March 11, 2024