Bummer! This is just a preview. You need to be signed in with a Treehouse account to view the entire video.
MASH Choice and Random Number Functions2:37 with Joy Kesten
A detailed description of how the MASH Choice and Random Number functions work.
Math.floor - always round down
Math.ceil - always round up
Math.round - round naturally
|| - or
The mass choice function works because it gets a random number between zero and
three and then uses that number to pull out an item from our array and
then returns that number.
Now, to get that random number we have to use the random number function
from up here.
You'll notice that the random number function has a parameter num.
We use that down here.
This lets us provide a number if we want to change what our highest number can be.
So if you decide to add three more items to the arrays here or
in your form you're gonna have to change these numbers so
that this function will choose from all the items.
In the next video, we'll learn more about stuff we can change but for now,
let's keep thinking about the functions.
In the random number function,
the first thing we did is create a variable called num.
This is either a number we pass in or, and these two pipes mean or, four.
Now Java script starts counting at zero so
in our columns it starts counting at zero, one, two and three.
Now you might think that our
highest number can be four cuz it says it right here but
the next line explains why it's three and not four.
In this line we use Math.random, which will give us a decimal
number between zero and one, and then we multiply it by our number.
Now if you've done multiplication with decimals,
you'll know this will give us a number lower than num.
So let's say that our num is ten and math.random gives us 0.67.
When we multiply 0.67 and 10 we get 6.7.
But then, because all of this is inside of Math.floor,
the number will be rounded down, no matter what.
Which means our 6.7 becomes six.
Now, your math teacher will tell you to round 6.7 to seven but
Math.floor means always round down.
If you want a few other ways to round numbers, I've put a few bits of code
in the teacher's notes and you should try these out.
Finally, the return gives back the number we've now calculated.
Now that you've learned how everything works independently and
together, let's change some stuff.
You need to sign up for Treehouse in order to download course files.Sign up