Math Random Function (
Math.random()) is a random number generator that returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1).
It’s syntax looks like –
First, create a variable random and assign a random number to it using a random function.
let random = Math.random();
Now, we are checking the value of random with the console log and also multiply value of 2 to a random variable.
console.log(random * 2);
Any guess, what should the output of the above statement?
Now, you know the answer is “>=0 or <2“. But why it’s not a fixed answer and range is their.
So, the random function gives the random number and by default, their range is greater than equal to 0 but less than 1.
Because of this, math random function output value is unpredictable. If you run random function 10 time then it gives you 10 different value. Which are less than one.
So, when you multiply 2 with random number than their range increases to 2 but less than 2.
At last, That’s why we get an answer “0> & <2“.
Let me know in the comment section, what you think about it.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – can NaN be really equal to NaN
- JS Quiz – string match regexp can extract a number value
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.