📏 Create an array of a given length in JS

const createArray = (length: number, value: any = null) => {
  return new Array(length).fill(value);

const emptyArrayOfLengthFive = createArray(5);
// [null, null, null, null, null]

// If we had used new Array(5) we would have
// [ <5 empty items> ]

If you want to create an array in JavaScript of a given length you can use the Array constructor plus the fill method combined. The first one will create a new array of given length but it will be empty, if you try to iterate over it you'll notice that there will be 0 iterations. This is where the fill method comes into action, by using it we'll be inserting the given value in all the elements of the array. Now the resulting array is filled and we can iterate over it.