Search code snippets, questions, articles...

Lodash - Get random number between two numbers

If you are using the Lodash library in your project and creating a program to get random numbers between the two numbers then you can use the Lodash random() function and do that with a single line of code.
// Get random number between two numbers
const random_number = _.random(1, 100);

Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool


Random number is: 75

Live demo of the above code

The above code output will be different when you run the code. We are generating a random number between 1 to 100 using the code example.

By default, Lodash provides a lot of in-built functions that can be helpful to prevent rewriting your javascript code. The random() function is one of them. The full explanation of the _.random() function is as below.

_.random() function in Lodash

To get a random number between a lower value and an upper value you can use the _.random() function. It takes one required parameter upper value. If you have not passed the lower value, it will consider the lower value 0.

The third parameter is the floating-point number. It is false by default but if you want your random number in floating type then you can pass it to true.


_.random(lower_value, upper_value, floating)

Code Example

// random number between 0 and 10
const n1 = _.random(10);

// random number between 2 to 20 as float value
const n2 = _.random(2, 20, true);

// random number between 1.7 to 10.4 as float value
const n3 = _.random(1.7, 10.4);



Live demo of the above code

Get a random number between 1 to 10 using Lodash

When we are working on an application where we need to generate random numbers between 1 to 10, we create our function in javascript and then use it. But if you are using the Lodash library then you can easily do it using its in-built function.

Below is an example to generate a random number between 1 to 10

// get random interger value from 1 to 10
const result = _.random(1, 10);

// get random float value between 1 to 10
const float_random = _.random(1, 10, true);



Live Demo

Was this helpful?