I have read that Math.random() returns a result between 0 and 1.

In this example, if Math.random() returns 1, then it will round to 1, return 7, and the index will be out of range.

Is this an issue or is 1 excluded with 0.999 being the max?

```
const colors = ['red','orange','yellow','green','blue','rebeccapurple','violet'];
function change() {
document.body.style.background = colors[Math.floor(7*Math.random())];
}
```

**Link to content:** Learn to Code with JavaScript - Section 1

According to the spec, `Math.random()`

returns a Number value with positive sign, greater than or equal to 0 but less than 1.

That means that the result of multiplying `Math.random()`

by seven will always be less than 7.

As Math.floor() returns a number representing the largest integer less than or equal to the specified number, the result of `Math.floor(7*Math.random())`

will never be greater than 6.

There *are* 7 elements in the array, but arrays in JavaScript are zero indexed, so no, it’s not an issue.

1 Like