In JavaScript arrays are fairly straight forward in the sense we don’t have to worry about allocating their size most of the time because that will all be handled for us.
However there are occasions where it does come in handy to be able to initialize an array with n values in JavaScript where n is the size we want.
In this post we will go over how to initialize an empty array in JavaScript and then fill it as well.
How to initialize an array with values in JavaScript
To initialize and fill an array with n values in JavaScript, one of the easiest ways is to make use of the Array.prototype.fill method which let’s us fill an empty array with a given value.
All we have to do is firstly, create an empty array with a size of n, and then call Array.prototype.fill on it to give the empty array values of our choice.
Here is an example of how to initialize array with values in JavaScript:
const n = 2;
const value = "example";
const newArray = Array(n).fill(value);
console.log(newArray); // ["example", "example"]
Summary
There we have how to initialize an array with values in JavaScript, if you want more like this be sure to check out some of my other posts!