An Exploring South African

Menu

How to Generate a Random Number in JavaScript Programming13 AUG 2013

Generating a random number in JavaScript is a relatively easy thing – we simply made use of JavaScript’s built in random() function, part of the JavaScript Math object.

The random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).

If we then combine this method with the floor() method (also from the JavaScript Math object – Give x, returns x, rounded downwards to the nearest integer), then it becomes trivial to quickly generate a random number.

For example:

//Return a random number between 1 and 10:
Math.floor((Math.random()*10)+1);
//Return a random number between 1 and 50:
Math.floor((Math.random()*50)+1);