How to Fill an Array with Random Numbers in JavaScript Using an Arrow Function?

Estimated read time 1 min read

You can fill an array with random numbers in JavaScript using an arrow function and the Array.from() method. The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.

Here’s an example:

const array = Array.from({length: 5}, () => Math.floor(Math.random() * 100));

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

In this example, {length: 5} creates an array-like object with a length of 5. The arrow function () => Math.floor(Math.random() * 100) generates a random number between 0 and 100 (inclusive). The Array.from() method creates a new array with 5 elements, each element being the result of calling the arrow function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply