How to get a random value from a JavaScript array

October 13, 2022 No comments javascript random

Introduction

In JavaScript, we may wish to get a random value from an array. In this post, we'll look at how to do it.

How to get a random value from a JavaScript array

To get a random value from a JavaScript array we can use Math.floor() and Math.random() functions:

const frontbackend = ["A", "B", "C", "D", "E", "F", "G"];

const random = Math.floor(Math.random() * frontbackend.length);

console.log(random, frontbackend[random]);

In the following example, we use the Math.random() function to get a pseudo-random number between 0 and 1. Then we multiply that value by array.length to get a random value no greater than the size of the array. Finally, we used Math.floor() that rounds down a given number.

The random variable contains a random index of frontbackend array.

Conclusion

In this post, we presented the best way to get a random value from a JavaScript array.

{{ message }}

{{ 'Comments are closed.' | trans }}