How to Fill an Array with Random Values in JavaScript?

Estimated read time 1 min read

You can fill an array with random values in JavaScript by using a loop such as for or while and generating random values within a specific range using the Math.random() method.

Here’s an example using a for loop:

const array = [];
const max = 100;
const min = 1;

for (let i = 0; i < 5; i++) {
  array.push(Math.floor(Math.random() * (max - min + 1)) + min);

// Output: [34, 67, 12, 56, 9]

In this example, the Math.random() method generates a random value between 0 (inclusive) and 1 (exclusive). By multiplying the random value by max - min + 1 and adding min, we get a random value within the desired range of min to max. The Math.floor() method rounds down the resulting value to the nearest integer.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply