Built in functions are there for our convenience and follow along lines of common purposes. There is no assuming, only assessing requirements of our code design. It is us who set the criteria.
Math.random()
only generates a float (a decimal fraction) less than 1 and equal to or greater than 0. When we multiply that by a whole number we still have a float. If our requirement is a whole number then we must reach into the tool box for another tool… Math.floor()
or Math.ceil()
. One will give us the small integer, by truncating, the other will give the larger integer by rounding up to it.
As far as generating random integers, we only need to know the upper bound of the range. For a die with six sides, the upper bound is 6
.
Math.random() * 6
will give us a number between 0, inclusive, and 6, exclusive. To make that into a whole number from 1 to 6 inclusive, we floor the value then add 1.
These are not assumptions but action steps that we design into our program. Put the idea of assuming anything right out of your mind and gain familiarity with the built in functions as they are presented. Explore and learn. This is how you build knowledge and confidence.
A lot of the learning process involves experimenting with different ideas. Form a hypothesis (a guess, essentially) of an expected outcome based on our experience, write the code and test it. If the outcomes don’t match our expectations then it is up to us to resolve the reason why.
Code is built around promises. A given built in promises a certain outcome and we can count on that outcome (or range of outcomes) every time. Our code must operate on the same premise. We promise the user a certain outcome or result and our code must deliver upon that promise every time, or have a good fall back in the event it does not.
Here is a famous lecture by the late Professor Richard Feynman:
Richard Feynman Teaches you the Scientific Method - Farnam Street
Ultimately it is our responsibility to work toward removing of guess work and replacing it with functional code that works because we know it will. Keep at it. If you must guess, then test, test, test and don’t be disappointed if you guessed wrong. By process of elimination, that is one guess you can check off.