How to Create an Empty Array of a Given Size in JavaScript

Here are five ways to create an empty array of a given size in JavaScript.

  1. Using the new operator (Array constructor)
  2. Using the spread operator
  3. Using Array.fill() method
  4. Using Array.from() method
  5. Using apply() and map()

Method 1: Using the new operator (Array constructor)

The easiest way to create an empty array of a given size is to “use the new operator.”

let numberArray = new Array(10);

console.log("The length=" + numberArray.length);

console.log(numberArray);

Output

The length=10
[ <10 empty items> ]

Method 2: Using Array Spread Operator

You can also use the spread operator with Array constructor to construct an empty array.

const arr2 = [...new Array(10)];

console.log("The length=" + arr2.length);

console.log(arr2);

Output

The length=10
[
  undefined, undefined,
  undefined, undefined,
  undefined, undefined,
  undefined, undefined,
  undefined, undefined
]

Method 3: Using an Array.fill() method

You can use the Array.fill() method to fill the undefined values to an array of a given size to create an empty array.

const arr3 = Array(10).fill(undefined);

console.log("The length=" + arr3.length);

console.log(arr3);

Output

The length=10
[
  undefined, undefined,
  undefined, undefined,
  undefined, undefined,
  undefined, undefined,
  undefined, undefined
]

Method 4: Using the Array.from() method

In ES6, a new Array method is introduced called Array.from() method, which can be helpful in creating an array of a given size.

const arr4 = Array.from(Array(10));

console.log("The length=" + arr4.length);

console.log(arr4);

Output

The length=10
[
  undefined, undefined,
  undefined, undefined,
  undefined, undefined,
  undefined, undefined,
  undefined, undefined
]

Method 5: Using apply() and map()

let arr5 = Array.apply(null, Array(10))
           .map(function () { });

console.log("The length=" + arr5.length);

console.log(arr5);

Output

The length=10
[
  undefined, undefined,
  undefined, undefined,
  undefined, undefined,
  undefined, undefined,
  undefined, undefined
]

Conclusion

An Array() constructor with the fill() method is a clean and concise way to create and initialize an array. The fill() method ensures that the array slots are correctly initialized, making subsequent operations on the array more predictable.

Related posts

JavaScript Array Length

Create a Zero Filled Array in JavaScript

Leave a Comment