Categories
JavaScript Answers

How to Set All Values of an Array with JavaScript?

Spread the love

To set all values of an array with JavaScript, we can use the fill method

For instance, we can write:

const arr = [...Array(20)].fill(10)
console.log(arr)

We create an array with 20 empty slots with Array(20).

Then we spread that into a new array to create an array with 20 undefined entries.

Next, we call fill with 10 to replace will the undefined values with 10.

Therefore, arr is:

[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

as a result.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *