Random numbers | JavaScript essentials

/ #JavaScript


Generating random number using JavaScript isn't hard, but you need to know how to do it.

Random numbers explained

By using a built in function called "Math.random()" we can get a random float between 0 and 1. The problem is that most times, you want a random integer.

To get a random integer, you need to use something called "Math.floor()". This is a function for rounding up or down. But this still isn't enough to get what we want.

We also need to multiply the value from "Math.random()" by 10.

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

If you want to get a value between 1 and 10, you need to do the following:

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

This will do the same as above, but it makes sure that the value is at least 1 and that it can go as high as 9 + 1.

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.