Categories
JavaScript Answers

How to create an array with random values with JavaScript?

Spread the love

Sometimes, we want to create an array with random values with JavaScript.

In this article, we’ll look at how to create an array with random values with JavaScript.

How to create an array with random values with JavaScript?

To create an array with random values with JavaScript, we can use the Array constructor and the Math.random method.

For instance, we write

const arr = Array(40)
  .fill()
  .map(() => Math.round(Math.random() * 40));

to call Array with 40 to create an array with 40 empty slots.

Then we call fill to fill the slots with undefined.

And then we call map with a callback that returns a random number between 0 and 40 for each slot with Math.random rounded to the nearest integer with Math.round.

Conclusion

To create an array with random values with JavaScript, we can use the Array constructor and the Math.random method.

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 *