Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
A detailed description of how the MASH Choice and Random Number functions work.
More Math
Math.floor  always round down
Math.ceil  always round up
Math.round  round naturally
  or

0:00
The mass choice function works because it gets a random number between zero and

0:05
three and then uses that number to pull out an item from our array and

0:11
then returns that number.

0:13
Now, to get that random number we have to use the random number function

0:18
from up here.

0:19
You'll notice that the random number function has a parameter num.

0:24
We use that down here.

0:26
This lets us provide a number if we want to change what our highest number can be.

0:32
So if you decide to add three more items to the arrays here or

0:37
in your form you're gonna have to change these numbers so

0:41
that this function will choose from all the items.

0:45
In the next video, we'll learn more about stuff we can change but for now,

0:49
let's keep thinking about the functions.

0:51
In the random number function,

0:53
the first thing we did is create a variable called num.

0:57
This is either a number we pass in or, and these two pipes mean or, four.

1:03
Now Java script starts counting at zero so

1:07
in our columns it starts counting at zero, one, two and three.

1:10
Now you might think that our

1:16
highest number can be four cuz it says it right here but

1:20
the next line explains why it's three and not four.

1:26
In this line we use Math.random, which will give us a decimal

1:31
number between zero and one, and then we multiply it by our number.

1:38
Now if you've done multiplication with decimals,

1:40
you'll know this will give us a number lower than num.

1:44
So let's say that our num is ten and math.random gives us 0.67.

1:50
When we multiply 0.67 and 10 we get 6.7.

1:58
But then, because all of this is inside of Math.floor,

2:03
the number will be rounded down, no matter what.

2:06
Which means our 6.7 becomes six.

2:10
Now, your math teacher will tell you to round 6.7 to seven but

2:15
Math.floor means always round down.

2:19
If you want a few other ways to round numbers, I've put a few bits of code

2:23
in the teacher's notes and you should try these out.

2:25
Finally, the return gives back the number we've now calculated.

2:31
Now that you've learned how everything works independently and

2:35
together, let's change some stuff.
You need to sign up for Treehouse in order to download course files.
Sign up