How to initialize an array with values in JavaScript

How to initialize an array with values in JavaScript image

In this post we cover how to initialize an array with values in JavaScript

Initializing arrays with values in JavaScript can be done in two steps. Firstly creating an array of length n and then filling the array with a given value using the Array.prototype.fill method.

Here is an example of how this can be done:

1const n = 2;
2const value = "Coffee";
3const newArray = Array(n).fill(value);
4console.log(newArray); // ["Coffee", "Coffee"]

JavaScript

JavaScript is a programming language that is primarily used to help build frontend applications.

It has many uses, such as making network requests, making dynamic or interactive pages, creating business logic and more.

Array.prototype.fill

Array.prototype.fill is a method on arrays that can be used to fill or change all the values in an array to a given value.

It can accept three arguments, two of which are optional.

The first argument is the value that is going to "fill" the array.

The second is an integer that corresponds to the index for where in the array to start the fill from.

And the third is another integer that corresponds to the index for where to end the fill.

Further resources

Related topics

Save code?

How to initialize an array with values in JavaScript code example image

© 2024 MWXYZ