This post will discuss how to create an empty array of a specific size in JavaScript.

An empty array is an array that has no elements, but has a defined length property. Creating an empty array of a specific size in JavaScript can be useful for various purposes, such as initializing data structures, pre-allocating memory, or generating test cases. There are several ways to achieve this, depending on the desired behavior and compatibility of the code. Here are some common functions:

1. Using Array constructor

One common way to create an empty array of a specific size is to use the Array constructor. We can use the Array constructor with a single numeric argument, which creates an array with that many empty slots. The syntax is new Array(length) or Array(length), where length is a positive integer that specifies the size of the array. For example, if we want to create an empty array of size 5, we can do this:

Download  Run Code

 
This function is simple and easy, but it has some drawbacks. The array created by this function is sparse, meaning that it does not have any values assigned to its elements. Therefore, we cannot iterate over it or use functions like map(), filter(), or forEach() on it, and it may cause unexpected results when used with other functions like join() or toString(). To fix this problem, we can use the Array.fill() function with a value of undefined, which fills an array with that value. For example,

Download  Run Code

 
It should be noted that if we pass more than one argument to the Array constructor, it will create an array with those arguments as elements instead of using them as the length. For instance:

Download  Run Code

2. Using Array.from() function

Another way to create an empty array of a specific size is to use the Array.from() function. This function creates a new array from an iterable or array-like object. So, if we want to create an empty array of a given size, we have to pass an object to the Array.from() function having only a single key length, which specifies the size of the array to be created. For example, if we want to create an empty array of size 5, we can do this:

Download  Run Code

 
This function is more flexible and reliable than the previous one, as it creates a dense array with undefined values at every index. Therefore, we can iterate over it and use functions like map(), filter(), or forEach() on it, and it behaves as expected with other functions like join() or toString(). Also, this function works for any value of the length property, even if it is not a number. However, it requires ES6 support, which may not be available in some older browsers.

That’s all about creating an empty array of a specific size in JavaScript.