Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ā¤ šŸ’»
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

JavaScript - random integer number in range with exclusive max value example

0 contributions
9 points

In JavaScript, it is possible to randomizeĀ integer numberĀ in range with exclusive max value in following way.

1. Custom random methodĀ examples

// ONLINE-RUNNER:browser;

	inclusive min (result can be equal to min value)
    exclusive max (result will not be to max value)
function randomizeInteger(min, max) {
  	if(max == null) {
    	max = (min == null ? Number.MAX_SAFE_INTEGER : min);
      	min = 0;

    min = Math.ceil(min);  // inclusive min
    max = Math.floor(max); // exclusive max

  	if(min > max - 1) {
    	throw new Error("Incorrect arguments.");

    return min + Math.floor((max - min) * Math.random());

// Example:

console.log(randomizeInteger()); // 5547382624322139
console.log(randomizeInteger(5)); // 3
console.log(randomizeInteger(10, 80)); // 62
console.log(randomizeInteger(-50, 50)); // -8

See also

  1. JavaScript - Math.random() method example
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey šŸ‘‹
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more