Search code examples
javascriptarraysmathrandomfloor

Understanding the use of Math.floor when randomly accessing an array


I used a code I found on this site to access an array of string values. I changed the variable names, but other than that, the code remains the same.

var rand = array[Math.floor(Math.random() * array.length)];

It works, and as I understand it, (Math.random() * array.length) is the area which generates the random number itself, so why is Math.floor required? I am clearly not understanding something quite obvious here.


Solution

  • Math.floor returns a whole number, while Math.random() will return a float between 0 and 1.

    To access an item in an array, like rand[0], you need to have a whole number. You cannot access an item in array with rand[1.43].

    That little line of code is going to access a random item in an array by generating a random float from zero to the array's length, and rounding it to its nearest whole number with Math.floor