Display a random word in a list of words using Javascript

javascript

Ever have a list of values and you want to pick a random item in the list?

Here’s how I would do this.

First, we start with our random number function, as follows:

function randomNum(minVal, maxVal) {
	do {
		r = Math.random();
	} while (r == 1);
	return minVal+Math.floor(r*(maxVal+1-minVal));
}

The randomNum function, accepts two argument, minimum value (minVal) and a maximum value (maxVal),  these will be the lowest number and the highest number in your range of numbers, it returns a random number between the two numbers passed to it.

So lets say you have an array of words, something like this:

var greeknumbers = new Array();
greeknumbers[0] = "alpha";
greeknumbers[1] = "beta";
greeknumbers[2] = "gamma";
greeknumbers[3] = "delta";
greeknumbers[4] = "epsilon";
greeknumbers[5] = "zeta";
greeknumbers[6] = "omega";
greeknumbers[7] = "sigma";
greeknumbers[8] = "psi";
greeknumbers[9] = "chi";

If we wanted to get a random item from this list, we would do the following:

console.log(greeknumbers[randomNum(0, greeknumbers.length)]);

Lets break-down what this is doing, starting from the inside.

The randomNum function is being executed, and has zero (0) passed into it as the minVal, and the length of our array as the maxVal (in this case, it would be 10).

randomNum(0, greeknumbers.length);

If we were to execute this in our console, we would see a random number in between 0 and 10.

To refer to a specific item in our array, we can refer to a specific array index:

greeknumbers[0]; //this will return "alpha", the first item in our array.

So in our above example, all we are doing is passing a random number to our array, which in turn displays the random value at that array index!

Try it yourself, or you can download an example of this here: random-words-in-a-list.js.

I hope this was helpful to you, let me know if you have any other ways of doing this, I’d be curious to know!

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>