Snippets

Michael Gale Random number between X and Y

Created by Michael Gale
var startFrom = 1;
var countTo = 3;
var rand = Math.floor(Math.random() * countTo) + startFrom; 

// alternatively expressed as:
rand = Math.floor(Math.random() * 3) + 1; // returns 1, 2 or 3

//     1. Math.random()
//     returns a floating-point, pseudo-random number in the range (0, 1) eg 0.546237231211

//     2. 
//     * `countTo` == 3.546237231211

//     3.
//     Math.floor()
//     returns the largest integer less than or equal to a given number.

//     4. 
//     + 1
//     ensures number returned is always at least 1.

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.