Blog

Examples of Choosing Random Numbers in JavaScript
Posted on June 8, 2015 in JavaScript by Matt Jennings

// Returns a random number between 0 (inclusive) and 1 (exclusive)
Math.random();

// Returns the largest integer less than or equal to a number
// Example below returns 1:
Math.floor(1.5);

// Returns a random number between 1 and 10 (inclusive of both)
Math.floor((Math.random() * 10) + 1);


/*
Function that returns a random number between maximum and minimum
integers provided (inclusive of both)

Example below a random integer between -1 (max) and -5 (min) inclusive of both:
*/
function randomIntFromInterval(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

console.log(randomIntFromInterval(-5, -1));

Leave a Reply

To Top ↑