Snippets

Get a random number with JavaScript Lodash

Posted by I. B. Gd Pramana A. Putra, 18 Aug 22, last updated 18 Aug 22

Lodash has a convenient way to generate a random number, here's how you can get a random number with JavaScript Lodash:

const result = _.random(1, 100);
console.log(result);

Output

The output could be any number from 1 - 100.

Quick guide:

_.random(0, 5);
// => an integer between 0 and 5
 
_.random(5);
// => also an integer between 0 and 5
 
_.random(5, true);
// => a floating-point number between 0 and 5
 
_.random(1.2, 5.2);
// => a floating-point number between 1.2 and 5.2

Reference: Lodash Docs

I love sharing code snippets as most of the time, a quick code example is what we're looking for instead of long-written articles. If you think my code snippets are helpful and save you a lot of time, please consider buying me a cup of coffee :)

Support me via · paypal · buymeacoffee · ko-fi · trakteer
Contributed Snippets
Answer & Responses
    No comments yet

Wanna write a response?

You have to login before write a comment to this post.