One such collection contains mathematical methods, aptly named the Math library.
Let’s see how you call the .random() method from the Math library:
console.log(Math.random()); // random number between 0 and 1
In the example above, we called the .random() method by appending the library name with a period, the name of the method, and opening (() and closing ()) parentheses. This method returns a random number between 0 and 1. This code prints a random number between 0 and 1.
To generate a random number between 0 and 50, we could multiply this result by 50, like so:
Math.random() * 50;
Math.floor(Math.random() * 50);
In this case:
- Math.random generates a random number between 0 and 1.
- We then multiply that number by 50, so now we have a number between 0 and 50.
- Then, Math.floor rounds the number down to the nearest whole number.
Play with the code below to continue practising your coding skills with math.random and math.floor. Try to make your program generate a random number from 0 to 99.