This post will discuss how to declare an empty array in JavaScript.

An empty array is an array that has no elements in it. There are two main ways to declare an empty array in JavaScript: array literal notation and the Array constructor. Here are some examples of both functions:

1. Using an array literal

This is the simplest and most common way to create an empty array. We just use a pair of square brackets to indicate an array with no elements. Here’s an example:

Download  Run Code

2. Using Array constructor

This is another way to create an empty array, but it is less concise and less preferred than the array literal function. We use the new keyword and the Array() constructor function to create an array object with no arguments. Here’s an example:

Download  Run Code

 
Both functions will result in an array with a length of zero and no elements. However, there are some differences between them. For example, the array literal is more concise and readable, while the Array constructor can take arguments to specify the size or the elements of the array. Here’s an example:

Download  Run Code

 
Note that using the Array constructor with a single numeric argument will create an array with that many empty slots, not an array with that number as its only element. To create an array with a single number element, we need to use an array literal or wrap the number in another pair of brackets. Here’s an example:

Download  Run Code

 
In general, it is recommended to use the array literal function to declare an empty array in JavaScript, as it is simpler, faster, and less error-prone than the Array constructor function.

3. Using Array.of() or Array.from() function

The array literal and the Array constructor are two main ways to declare an empty array in JavaScript, as well as some variations. These variations are less common and may have some drawbacks, such as performance issues or confusion. Therefore, they are not recommended.

1. The Array.of() function creates an array from a variable number of arguments. If no arguments are given, it creates an empty array:

Download  Run Code

 
2. The Array.from() function creates an array from an iterable or an array-like object. If the object is empty, it creates an empty array:

Download  Run Code

That’s all about declaring an empty array in JavaScript.