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);
console.log(random_number);
Output
Random number is: 75
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.
Syntax
_.random(lower_value, upper_value, floating)
Code Example
// random number between 0 and 10
const n1 = _.random(10);
console.log(n1);
// random number between 2 to 20 as float value
const n2 = _.random(2, 20, true);
console.log(n2);
// random number between 1.7 to 10.4 as float value
const n3 = _.random(1.7, 10.4);
console.log(n3)
Output
7
11.817919421376114
2.1816681956885513
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);
console.log(result);
// get random float value between 1 to 10
const float_random = _.random(1, 10, true);
console.log(float_random);
Output
7
8.869338108953528
- Javascript to get the number of days between two dates
- add sum of numbers of given numbers
- Javascript program to swap two numbers without using temporary variable
- Lodash - merge two arrays and remove duplicates from it
- Lodash - Check if a number is within the Range(without if-else)
- Replace multiple spaces between words with single space using javascript
- Random & Unique CSS Gradient-Color Generator