Randomness in JavaScript

Random Function

Math.random() can be used to generate random numbers. This can be useful in many circumstances. For instance, maybe you need to keep track of every user who visits your website. We could use this function to assign a random number to each user.

Math.random() is a powerful function, but it’s important to remember that its output is very simple. It simply generates a number between 0 and 1:

Math.random(); // 0.9214621770661324

Rounding Numbers

You can round numbers in three ways with Javascript:

  • Math.round();
  • Math.ceil();
  • Math.floor();


This function will return a value rounded to the nearest whole number:

Math.round(3.5); // 4
Math.round(3.4); // 3


This function rounds up to the nearest whole number:

Math.ceil(3.5); // 4
Math.ceil(3.4); // 4


This function rounds down to the nearest whole number:

Math.floor(3.5); // 3
Math.floor(3.4); // 3

Random Array Values

You can also use the Math.random() function to select a particular key within an array.

Let’s imagine we have an array of 6 images:

var images = ["image1.jpg", 

As we know, calling images[0] will return image1.jpg. If we want to select a key at random we need to find a random number between 0 and the total keys within the array.

Array Length

Use length to determine the to length of an array:

images.length; // 6

Selecting a random number within a range

Now that we know how to find the total length of the array, we can use Math.random() to select a valid random number:

Math.random() * images.length; // 2.6803422393277287

Since we know we need a whole number and the highest value that would be valid is 5 given that we count the keys starting at zero, use Math.floor() to round down:

Math.floor(Math.random() * images.length); // 2

Putting it all together

The last step is to use this number in conjunction with the way that we retrieve a value for a given key:

images[2]; // 'image3.jpg'

var random_num = Math.floor(Math.random() * images.length); // 2

images[random_num]; // 'image3.jpg'

Setting CSS Values

Sets the width and height of .target to a random value between 20 and 80:

var sizeVal = (Math.floor(Math.random()*60) + 20) + "px";

$(".target").css("width", sizeVal).css("height", sizeVal);

In-class Example:

See below for the JavaScript source to our in-class example: