dimanche 19 janvier 2020

JS, let x = (Math.random()*2|0) output explanation [duplicate]

Hello and thanks for stopping by.

I am still green behind the ears and I'm trying to understand the output of this code.

let x = (Math.random()*2|0) 

It basically gives either 0 or 1. Why is that?

Is it because the random * 2 is sometimes rounded up to 1? And how does | work here? Is it considered like a OR? ||

The original code I found:

var randomNum = ((Math.random () * 2 | 0) + 1) - 1;

Is there any difference?

Thanks for you help.




Aucun commentaire:

Enregistrer un commentaire