JavaScript Treehouse Club - MASH MASH - JavaScript Stuff You Can Change

Why is var num = num || 4 , and not var num = num || 3?

Hi all!!

This might be a stupid questions but: If Javascript starts counting from 0, and there are 4 choices, why is the 'var num' set on 4? Joy said herself that the 4 choices are counted as 3 for Javascript. (0= location, 1= pet, 2= profession, 3= home)

Thank you!

Nicolas

Filip lsze
Filip lsze
8,017 Points

It's a fine question. The reason is, as Joy's comment states, the first part of the function Math.random() * num generates a number BETWEEN 0 and the passed in Number. So possible values between 0 and 4 would be :

1.23425645045676
3.98354675839096
0.821131208463277

Then the function performs a Math.floor() on the generated number rounding it down to the nearest integer. The above examples become

1
3
0

You are totally correct about the 4 choices being counted as 0-3, and after the rounding down, this is exactly what the function produces.

Filip Olszewski Thank you!

4 Answers

Zachary Billingsley
Zachary Billingsley
6,182 Points

Hello!

The reason it must be 4 instead of 3 is when you use Math.random it returns a number between the (inclusive) 0 and the (exclusive) 1, meaning that Math.random will never return 1. So if you multiple the random number by 4 and round down using Math.floor the highest number you can get is 3 the lowest will be 0.

Hope that helps!

Mario Vega
Mario Vega
8,170 Points

Hello,

The "num" variable isn't actually the number that's returned. Instead, it's used in the calculation in the line right below it.

Specifically, it is multiplied into a number between 0 and 1, which will always be less than 4. Then, when the Math.floor function is applied, you get an integer without the decimal places.

For example:

Let's say the Math.rand function returns .99.

.99 * 4 = 3.96, rounded down by Math.floor = 3.

Andrew McPheron
Andrew McPheron
14,290 Points

As a general recommendation, be sure to post code snippets for your questions as well. I was able to find the section in question from the video workspace, but it saves time if we can see what you're working with ahead of time.

To answer the question, it's actually related to how Math.floor and Math.random interact. Math.random makes a number with decimals where 1 > X >= 0. In other words, it could be 0 but it will never be 1, just really close to it. What Math.floor does is remove the decimals and round to the lowest integer/whole number. So if the random number is .99 and we multiply it by 4, we get 3.96. Floor cuts off the .96, leaving us with just 3.

In this program then, using num = 4 means it can be 1 of 4 results- [0, 1, 2, 3].

Andrew McPheron and Zachary Billingsley thank you very much for the fast reply! Your answer made it very clear.

Thank you both!

Zachary Billingsley
Zachary Billingsley
6,182 Points

You are very welcome! Happy coding!