My Books

Text Processing with JavaScript

Solve complex text validation, extraction, and modification problems efficiently in JavaScript.

Modern Async JavaScript

Delve into async features of JavaScript from ES2020 through ESNext. Start building custom asynchronous iterators and generators, and more for fast, lean code.

JavaScript Brain Teasers

Ready to test your JavaScript skills? Challenge yourself with these brain-teasing puzzles, supercharge your learning journey, and emerge as a JavaScript pro.

jQuery Random Number

A popular question on forums is how to create random numbers in jQuery. We don't really need to use jQuery for a simple task like this. The Math.random() method in JavaScript can be used to quickly create a random number between 0 and 1

But most of the time we need a whole number not a float,. In order to create a whole number, we can multiply the number generated by Math.random() by 10 and then round the number using the floor() method, like this:

Math.floor(Math.random()*10);

This creates a number between 1 and 10 (for example 7.668625892) and then rounds it to the nearest number, in this case 8. If we wanted a random number between 0 and 7 we could multiply it by 7, like the following:

 Math.ceil(Math.random()*7); // 1,2,3,4,5,6 or 7

Have your say