user3477993 - 8 months ago 31

Javascript Question

I'm facing problems understanding a simple notion. Below the code:

`var arr = [1, 3, 7, 9, 12, 5, 4, 6];`

var randomArr = Math.floor(Math.random()*arr.length);

console.clear();

console.log(randomArr);

What i don't understand from this, is why

`Math.floor(Math.random()*arr.length)`

`Math.floor(Math.random())`

`0`

`Math.floor(Math.random())`

`0`

`0`

`1`

`1`

`Math.floor(Math.random()*arr.length)`

`8`

This is what i don't understand at the moment and can't find anything on this matter.

Thanks.

Answer

`Math.floor()`

returns the largest integer less than or equal to a given number. In other words it rounds a number down to the closest integer.

In your code `Math.random()*arr.length`

could return a real number as `Math.random`

might return .3 and the array length is 8, so instead of the random array element being 2.4, you'll get 2, which makes way more sense if you want to be able to pick the index of an array element. If `Math.random()`

returned .5, then you'd get an interger, but the odds are that you wouldn't get an integer in most cases.

Breaking `Math.floor(Math.random()*arr.length)`

down:

`arr.length`

is 8`Math.random()`

returns a value from 0 up to but not including 1.`Math.floor`

rounds the result of 8 times`Math.floor`

down- Example using
`.3`

as the value returned from`Math.random()`

:

`Math.floor( .3 * 8)`

`Math.floor(2.4)`

`2`

So given the code `Math.floor(Math.random()*arr.length)`

you'll end up with a value from zero to seven, any of which could then be used with your `arr`

array like `arr[randomArr].`

Source (Stackoverflow)