I’ve been studying Javascript on codecademy.com and was inspired to make a virtual dice today!
var diceRoll = function(number){
return Math.floor(Math.random()*number + 1)
}
It might not look like much but it creates a function called diceRoll, which I can add any number of sides to and it will output a random number from 1 to n (n being any number*).
So if I execute diceRoll(20) it will return a number from 1 to 20!
It’s really easy. I’ll break it down:
var diceRoll = function(number)
Defines the function called ‘diceRoll’. Which accepts one variable called ‘number’ for the number of sides on the dice.
return Math.floor(Math.random()*number + 1)
Math.random() is a built in function that returns a number from 0 to 1, so it might return 0.423693 or 0.8142232.
We then take that random number and multiply (*) it by ‘number’, which is set by the user when they fire the function. Finally we add (+) 1 to the result which changes our range from 0 to 19 to 1 to 20 (you’ll see why). Let’s say that it’s set to 20, and Math.random() returns .43235. We multiply those two numbers together (20 * .43235) and get 8.647, we then add one, 9.647.
All of that is wrapped in the function Math.floor() which takes a number and cuts off the decimals making it into a whole number. So it will take our result of 9.647 and turn it into 9.
This is the number that is then returned! So our function rolls a 9!
* Technically only up to 18 quintillion