Generating random numbers with JavaScript (Part 1)
When it comes to a random number, it can be seen and categorized as either a decimal number or a whole number. I have introduced this article as the first part and will subsequently be coming with the second part of generating random numbers in JavaScript. Although, from my perspective, this concept went in the breeze when I first came across it. I will be mentioning code snippets for each case in order to understand the working behind it.
There are two sides to this. Lets take each of them as we have discussed above:
1) Generate a random number in case of a decimal number
In order to generate a random number, we use the following function: Math.random();
This function generates and returns a random number in decimal which ranges between 0 (inclusive) and not quite up to 1 (exclusive). Consider the following code snippet:
function randomNum() {
return Math.random();
}
var result = console.log(randomNum());
When I was first using this function, it returned 0.43155545954686847 and saves it in the result variable. After playing with the code, the function returned different random decimal numbers within the range of 0–1 i.e starting from 0 and not completely up to 1.
2) Generate a random number in case of a whole number
As we discussed above, we learnt that it is great to a generate random decimal number, but generating a random whole number is more useful. Consider the following code snippet:
function randomWholeNum() {
return Math.floor(Math.random() * 10);
}
var result = console.log(Math.floor(Math.random() * 10));
The above returns a random integer number between 0 to 9.
The above code works as follows:
Use Math.random() to generate a random decimal number.
Multiply the random decimal number by 10.
Using Math.floor(), round off the decimal number down to its nearest whole number.
Hope you find this article beneficial and worthy!
Happy Coding!