Skip to main content

How to Initialize Sized or Filled Arrays in JavaScript

·2 mins

While you can easily initialize an empty array in JavaScript like, const arr = []. Depending on your project you may find the need to index a pre-sized array. Well look no further! I will show you all the ways you can.

Array of a certain length #

Array(9) will give you an array with a length of 9 but will have undefined values.

> const arr = Array(9)
> console.log(arr)
[<9 empty items]
> arr[2] = "hello";
> arr[4] = "world";
[ <2 empty items>, 'hello', <1 empty item>, 'world', <4 empty items> ]

Array of a certain length prefilled with same value #

This is when you would like to create a boolean array or a zeroed array.

> Array(9).fill(false);
[ false, false, false, false, false, false, false, false, false ]
> Array(9).fill(0);
[ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

Array of a certain length prefilled with Arrays or Objects #

Well that should be easy right? We just do the same thing as before but this time pass an array.

> const arr = Array(9).fill([]);
> arr
[ [], [], [], [], [], [], [], [], [] ]

Looks good but what happens if we modify one of these subarrays?

> arr[0].push('hello world')
> arr
[ [ 'hello world' ], [ 'hello world' ], [ 'hello world' ], [ 'hello world' ], [ 'hello world' ], [ 'hello world' ], [ 'hello world' ], [ 'hello world' ], [ 'hello world' ] ]

They’re all changed! Due to how the fill method is implemented it add the same array reference to each index. So to solve this we will need to create a new subarray for each index.

> const arr = Array.from({ length: 10 }, () => i);
> arr
[ [], [], [], [], [], [], [], [], [] ]

> arr[0].push('hello world')
> arr
[ ['hello world'], [], [], [], [], [], [], [], [] ]

There we go!

Array of consecutive numbers #

We can also use this style of initializing arrays to create an array with consecutive numbers.

const nums = Array.from({ length: 10 }, (_, i) => i);
[
  0, 1, 2, 3, 4,
  5, 6, 7, 8, 9
]

Hope you learned something new and use that JS knowledge to build something awesome!