| by Arround The Web | No comments

Getting a Random Value From a JavaScript Array

To obtain a random element, a random index is required. A random index is an integer value that is greater than 0 but less than the number of elements of an array. For this purpose, use the Math.random() method with the Math.floor() method.

This post will describe the procedure to get the random value from a JavaScript array.

Getting a Random Value From a JavaScript Array

Use the “random()” method with the “floor()” method of the “Math” object as “Math.random()” and “Math.floor()”. More specifically, the Math.random() method takes a random value between (0, 1) and multiplies it by the length of an array to retrieve the numbers between (0-arrayLength). The Math.floor() function returns the array index starting from to (0 to arrayLength-1).

Syntax

Follow the below-provided syntax to get the random value from an array in JavaScript:

[(Math.floor(Math.random() * (array.length)))]

The expression enclosed in square brackets [] evaluates to a random array index.

Example

Create an array of languages named “array”:

const array = ["HTML", "CSS", "JavaScript", "Bootstrap", "jQuery"];

Call the Math.floor() method with the Math.random() method by multiplying it with the array’s length and store it in a variable “randomElement”:

const randomElement = array[(Math.floor(Math.random() * (array.length)))];

Print the random value from an array on the console:

console.log(randomElement);

It can be observed that while executing the above-given code it gives a random value:

You can also create a function for getting the random number and can access this function anywhere in your code:

Create a function called “getRandomElement()” that takes “array” as a parameter and returns the random element from the array:

function getRandomElement(arr) {
 return arr[Math.floor(Math.random() * arr.length)];
}

Call the function by passing an array as an argument:

console.log(getRandomElement(array));

Output

That’s all about getting the random value from a JavaScript array.

Conclusion

For getting a random value from an array, use the “Math.random()” method with the “Math.floor()” method. A random index is required to obtain a random element, which is obtained using the Math.floor() method. A random index is an integer value larger than 0 but less than the number of array elements. This post described the procedure for getting the random value from an array in JavaScript.

Share Button

Source: linuxhint.com

Leave a Reply