Categories
JavaScript Answers

How to initialize an array with a single value with JavaScript?

Spread the love

Sometimes, we want to initialize an array with a single value with JavaScript.

In this article, we’ll look at how to initialize an array with a single value with JavaScript.

How to initialize an array with a single value with JavaScript?

To initialize an array with a single value with JavaScript, we can create an empty array and then call map to map each entry to the value we want.

For instance, we write

const arr = [...new Array(1000000)].map(() => 42);

to create array arr with length 1000000.

And then we call map with a callback that maps each entry to 42.

Then arr has 1000000 42’s in it.

Conclusion

To initialize an array with a single value with JavaScript, we can create an empty array and then call map to map each entry to the value we want.

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 *