Get a random value from array in JavaScript

Today, we will show you how to get a random value from array in JavaScript with example.

Get a random value from array in Javascript, How to select a random element from array, Get a random item from an array, Picking a Random Item from an Array, Getting a random value from a JavaScript array, Create a Random Array Picker, Random values in JavaScript.

Let’s start with an example so you can understand easily. To get a random value, we have to generate a random index number and return it. This is the simple method colors[Math.floor(Math.random() * colors.length)] to get a random value from array.

How it works:

First, Use the Math.random() function to get index of array that returns a random value between 0 and 1.

Now, using the length property we can get the last index of array that is maximum number.

Then multiply the random number with the length of the array and round down that result by Math.floor.

Finally, using random index we can get a random value from array.

If you run this code, you will see the random colour name every time.

That’s it for today. Happy Coding!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *