Home Communities
IT Knowledge
Inspiration
Languages
EN

# JavaScript - generate array with 10 random numbers

0 points
Created by:
434

In this article, we would like to show you how to generate array with 10 random numbers in JavaScript.

Quick solution:

``````// ONLINE-RUNNER:browser;

const array = Array(10) // array size is 10
.fill()
.map(() => 50 * Math.random()); // numbers from 0-50 (exclusive)

console.log(array);``````

Note:

Use `Math.floor()` to get integers instead of float numbers. You can find practical examples in the sections below.

## 1. Using `Array.fill()` with `map()` method

In this example we take the following steps:

1. Create an array with size `10`,
2. Use `fill()` method to fill the `array` with specified values,
3. use `map()` method to call `Math.random()` to generate a random value for each element in the `array` (from 0-50 exclusive).

Practical example:

``````// ONLINE-RUNNER:browser;

const array = Array(10) // array size is 10
.fill()
.map(() => 50 * Math.random()); // numbers from 0-50 (exclusive)

console.log(array);``````

If you want to receive integers instead of float numbers use `Math.floor()` method:

Practical example:

``````// ONLINE-RUNNER:browser;

const array = Array(10) // array size is 10
.fill()
.map(() => Math.floor(50 * Math.random())); // numbers from 0-50 (exclusive)

console.log(array);``````

## 2. Using `Array.from()` method (ES6+)

In this example, we use `Array.from()` method to create an array with size `10` and fill it with random numbers.

Practical example:

``````// ONLINE-RUNNER:browser;

// The solution for ES6+
const array = Array.from({ length: 10 }, () => Math.random() * 50);
console.log(array);``````

If you want to receive integers instead of float numbers use `Math.floor()` method:

Practical example:

``````// ONLINE-RUNNER:browser;

// The solution for ES6+
const array = Array.from({ length: 10 }, () => Math.floor(Math.random() * 50));
console.log(array);``````

## Alternative titles

Join to our subscribers to be up to date with content, news and offers.