user3477993 - 1 year ago 59
Javascript Question

# I can't understand a piece of code

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)`
returns a random number each time while
`Math.floor(Math.random())`
always returns
`0`
? From my understanding,
`Math.floor(Math.random())`
will always return
`0`
since he generated a value between
`0`
and
`1`
(
`1`
not included), so shouldn't
`Math.floor(Math.random()*arr.length)`
always return
`8`
in my case?

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

Thanks.

`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].`

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download