{

Different ways to generate random numbers between two numbers in javascript


Learn multiple ways to generate random numbers between two numbers in javascript with examples.

For example, there are two numbers, min=1, and max=10. Random numbers between 1 and 10 are 1,2,3,4,5,6,7,8,9,10.

There are multiple ways we can generate random numbers.

Generate Random Numbers between two numbers with javascript?

Math.random() function generates random floating number between 0 and 1. It returns possible values are zero, less than 1, and exclude 1.

It returns float number, used Math.floor() to round the lowest number.

function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomNumber(1, 10));

It generates a random number between 1 and 10.

Similarly, The above function is simplified using ES6 arrow functions,

Here is an ES6 code to generate random numbers.

const getRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
console.log(getRandomNumber(1, 10));

Generate random numbers with underscore and lodash libraries

Underscore and lodash are javascript libraries, provide utility functions.

If you used these libraries in your application, use the random(min, max) function.

Here is a syntax

random(lower, upper, float-type)

lower is lower bound value and optional upper is upper bound value float-type is true, returns floating value

A random number is inclusive of lower and upper value

Returns an number between lower and upper value

_.random(1, 100);// returns integer number between 1 and 100
_.random(1, 1000);// returns integer number between 1 and 1000
_.random(10,true);// returns floating number between 1 and 10

Generate random numbers with random npm library

In Nodejs, random is an npm library that provides advanced utility functions for generating random numbers. It returns boolean, integer, and floating random values. It uses normal and poisson distribution using given parameters

Here is a command to install to node application.

npm install --save random

Here is an ES5 javascript code to generate random numbers

const random = require('random')
random.int(1, 10) // 8
random.float(1, 10) // 6.3

use import with ES6 to create the random object.

import random from 'random'
random.int(1, 10) // 8
random.float(1, 10) // 6.3

Conclusion

Learn multiple ways to return random numbers and float for given lower and upper values.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.