CyrefJS
CCyrefJS
فا
Back to documentation
Number/Since 1.38.0

randomInt

Returns a random integer between the specified minimum and maximum values, inclusive.

randomInt(min, max):number

Parameters

minnumberrequired

The minimum integer that can be returned.

maxnumberrequired

The maximum integer that can be returned.

Returns

number

Returns 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

01

Basic usage

Generates a random integer between 1 and 10, including both endpoints.

TypeScript
const result = randomInt(1, 10);

console.log(result);
// Random integer from 1 to 10
02

Single value

When min and max are equal, the only possible result is that value.

TypeScript
console.log(randomInt(5, 5));
// 5
03

Negative range

Negative integers can be used as the range boundaries.

TypeScript
const result = randomInt(-10, -1);

console.log(result);
// Random integer from -10 to -1
04

Range crossing zero

The range can contain both negative and positive integers.

TypeScript
const result = randomInt(-5, 5);

console.log(result);
// Random integer from -5 to 5
05

Large range

The function can generate integers from a larger inclusive range.

TypeScript
const result = randomInt(100, 1000);

console.log(result);
// Random integer from 100 to 1000
06

Non-integer bounds

Both min and max must be integers.

TypeScript
randomInt(1.5, 10);
// RangeError: randomInt: min and max must be integers
07

Invalid range

The minimum value cannot be greater than the maximum value.

TypeScript
randomInt(10, 1);
// RangeError: randomInt: min must be less than or equal to max
08

Inclusive endpoints

Both min and max are valid possible results.

TypeScript
const result = randomInt(1, 3);

// Possible results:
// 1
// 2
// 3
Built with@cyref/js·Official documentation