1.38.0randomInt
Returns a random integer between the specified minimum and maximum values, inclusive.
randomInt(min, max):numberParameters
minnumberrequiredThe minimum integer that can be returned.
maxnumberrequiredThe maximum integer that can be returned.
Returns
numberReturns a random integer in the inclusive range from min to max.
Errors
Throws a RangeError if min or max is not an integer.
Throws a RangeError if min is greater than max.
Examples
Basic usage
Generates a random integer between 1 and 10, including both endpoints.
const result = randomInt(1, 10);
console.log(result);
// Random integer from 1 to 10Single value
When min and max are equal, the only possible result is that value.
console.log(randomInt(5, 5));
// 5Negative range
Negative integers can be used as the range boundaries.
const result = randomInt(-10, -1);
console.log(result);
// Random integer from -10 to -1Range crossing zero
The range can contain both negative and positive integers.
const result = randomInt(-5, 5);
console.log(result);
// Random integer from -5 to 5Large range
The function can generate integers from a larger inclusive range.
const result = randomInt(100, 1000);
console.log(result);
// Random integer from 100 to 1000Non-integer bounds
Both min and max must be integers.
randomInt(1.5, 10);
// RangeError: randomInt: min and max must be integersInvalid range
The minimum value cannot be greater than the maximum value.
randomInt(10, 1);
// RangeError: randomInt: min must be less than or equal to maxInclusive endpoints
Both min and max are valid possible results.
const result = randomInt(1, 3);
// Possible results:
// 1
// 2
// 3