Skip to content

Get random element from array JavaScript | Example code

  • by

Use Math.random * the length of the array, rounded down, as an index into the array to Get random elements from array JavaScript.

How to get a random element from array JavaScript Example

HTML example code:-

Get Random element from string array in JavaScript.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script> 

		var answers = ["A", "B", "C","D","E"];

		var randomAnswer = answers[Math.floor(Math.random() * answers.length)];

		console.log(randomAnswer);
	</script> 
</body> 
</html>	

Output: Your output maybe not same because this code gets random elements.

Get random element from array JavaScript

Do comment if you have any doubts and suggestions 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