Dec 1, 2020

Array(n) constructor

JavaScript Array constructor can be used in the follow syntax.

  const items1 = new Array(2); //(2) [empty × 2]
  //or 
  const items2 = Array(2); //(2) [empty × 2]

So you may think that, you can iterate the array using for/loop or method such as map, forEach with the newly created array. But it doesn't work.

for(let i = 0; i < items1.length; i++) {
   console.log(i);
}

// or 

const newItems = items1.map((value, index) => {
   return index;
});

Why? What this constructor or function does, is essenetially the following. It does not have anything inside, even though the length is set to 2.

  const items = [];
  items.length = 2;

If what you want is to initialize an array of a number of undefine value or any other value, you can do the following.

const items1 = Array(2).fill(); //(2) [undefined, undefined]
//or
const items2 = [...Array(2)];  //(2) [undefined, undefined]
//
const items3 = Array(2).fill().map((_, index) => index); //[0, 1]
//
const items4 = Array(2).fill('hello'); //['hello', 'hello']