JavaScript How “Math.random() * arr.length | 0” works for return a random index for an array

I've been working in a legacy code that have a certain functionality that should return a random item for array and I see the following expression:

array[Math.random() * arr.length | 0]

My first impression was try to undestand the | operator but i can't figure out how does work. I test the expression in the chrome console and I see that always returns a valid index with this:

let array = [1,2,3,4]
for(let i = 0; i < 5000; i++){
   console.log(array[Math.random() * arr.length | 0]);
}

How "Math.random() * arr.length | 0" works for return a random index for an array?

Answer:1
  • Math.random() returns a number >= 0 and < 1.
  • * arr.length returns a number >= 0 and < arr.length, yet this can't be used as an index, because it would have a fractional part
  • | 0 coerces the left expression to a integral number then applies the bitwise or with the number zero, which is always the other number

This said, what makes this work is the implicit conversion (called coersion) in the operator |.

Answer:2

HTML5 Workers can close themselves by calling the close() method. Is there a way to tell if the worker process is alive/running or if it has been closed? var myWorker = new Worker("worker.js"); ... ...

HTML5 Workers can close themselves by calling the close() method. Is there a way to tell if the worker process is alive/running or if it has been closed? var myWorker = new Worker("worker.js"); ... ...

i am working on developing on an Html page where i have two div. In each div i have one image. I want that each image should be visible for 2 second and after that the second div should get visible. ...

i am working on developing on an Html page where i have two div. In each div i have one image. I want that each image should be visible for 2 second and after that the second div should get visible. ...

  1. powerpoint slide show repeated

How do I submit the form? I have a simple search bar and a search button. The following enters the search string, but the click event is not fired. When headless is set to false and I manully click ...

How do I submit the form? I have a simple search bar and a search button. The following enters the search string, but the click event is not fired. When headless is set to false and I manully click ...

  1. puppeteer submit form wait

I have an application which is built with node.js and react.js and is universal (or "isomorphic" as they were called before) and speaks with REST API to get data. In render method of some component ...

I have an application which is built with node.js and react.js and is universal (or "isomorphic" as they were called before) and speaks with REST API to get data. In render method of some component ...