To create an empty array of a given size in JavaScript, you can use the Array()
constructor. The Array()
constructor creates a new array from an array-like object or iterable.
The Array()
constructor can have 0 to N number of parameters. But, if you pass only a single parameter to the Array()
, it creates an empty array of that size.
For example:
// Creates an empty array of size 5 const arr = new Array(5); console.log(arr); // Output: [empty × 5] // Creates an empty array of size 10 const arr1 = new Array(10); console.log(arr1); // Output: [empty × 10]
The Array()
constructor can be called with or without the new
keyword. In both cases, the Array()
creates a new instace of the array.
// Creates an empty array of size 5 const arr = Array(5); console.log(arr); // Output: [empty × 5]
Please remember, if you pass more than one parameters to the Array()
constructor, it creates array of those elements instead of creating an empty array.
For example:
// Creates an array of size 2 having elements 5 & 10 const arr = new Array(5, 10); console.log(arr); // Output: [5, 10]
If you do not pass any parameters to the Array()
, it will create an empty array of length 0.
// Creates an empty array const arr = new Array(); console.log(arr); // Output: [] console.log(arr.length); // Output: 0
Create Empty Array using Array.from() Method
You could also use the Array.from()
method to create an empty array of a given size. This method is used to create an array from an iterable or array-like objects.
So, if you want to create an empty array of a given size, you have to pass an object to the Array.from()
method having only a single key length
, which specifies the size of the array to be created.
However, the empty slots of the array in this method are by default filled with undefined
values.
Example:
// Creates an empty array of size 5 const arr = Array.from({length: 5}); console.log(arr); // Output: [undefined, undefined, undefined, undefined, undefined]
If you want to fill these empty slots with some other values, say zeros, you can use the Array.fill()
method. The Array.fill()
method fills each slot of the array with the specified value.
Let’s try to fill the above array slots with zeros:
// Creates an empty array of size 5 const arr = Array.from({length: 5}); // Fill each slot with 0 arr.fill(0); console.log(arr); // Output: [0, 0, 0, 0, 0]