Skip to content

JS get a random element from the Array | Example code

  • by

You can get a random element from the Array in JS by using Math.random() function to get the random number then Multiply it by the array length. After it, you will get numbers between zero to array length. Last use Math.floor() to get the index number from 0 to arrayLength-1.

JS get a random element from the Array Example

HTML example code:

<!DOCTYPE HTML> 
<html> 

<body> 

	<script> 

		function randomElement(items)
		{
			return items[Math.floor(Math.random()*items.length)];
		}

		var arr = [25, 45, 12, 65, 43];

		console.log(randomElement(arr));

	</script> 
</body> 
</html>	

Output: Your output could be not same because it select random element.

JS get a random element from the Array

Do comment if you have any doubts and suggestion on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading