Videos
Math.random returns a floating-point number between 0 and 1.
Returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.
Multiplying this by n gives a floating point number between 0 (inclusive) and n (exclusive).
Math.floor is then used to convert this floating point number to an integer between 0 and n - 1 (inclusive).
Why would anybody call Math.floor on a Math.random result?
In a nutshell, one calls Math.floor() when you want to truncate a decimal value to its nearest integer (by just dropping the decimal portion. So, 3.9 becomes 3, 2.1 becomes 2, etc... So, you would typically use that when you need an integer and you want the integer that is smaller than or equal to the decimal value. The math library also has Math.ceil() and Math.round(). Math.ceil() gets you the next larger integer, Math.round() rounds to the nearest integer going either up or down depending upon which is closer.
I've seen it used like:
Math.floor(Math.random() * num);
Breaking Math.floor(Math.Random() * num) down into it's individual pieces and explaining each piece, you get this:
Math.random() gives you a random decimal number between 0 and 1, including 0, but not including 1. So, it might give you something like 0.38548569372.
Math.random() * num gives you a random decimal number between 0 and num, including 0, but not including num. So, if num was 10, it might give you 3.8548569372.
Math.floor(Math.random() * num)) gives you a random integer number between 0 and num, including 0, but not including num. So, it might give you 3.
Math.floor() truncates the decimal number to only the integer portion. A random integer is often used for getting a random value from an array (which needs to be an integer).
why don't we use Math.ceil() instead of using the floor() function then adding 1, wouldn't it be much easier?
as stated in MDN reference about Math.random()
Returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.
Since Math.random can return 0, then Math.ceil(Math.random()*10) could also return 0 and that value is out of your [1..10] range.
About your second question, see Most efficient way to create a zero filled JavaScript array?
Math.floor() is preferred here because of the range of Math.random().
For instance, Math.random() * 10 gives a range of [0, 10). Using Math.floor() you will never get to the value of 10, whereas Math.ceil() may give 0.