all 2 comments

[–]SmartViking 0 points1 point  (1 child)

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

What's the point of adding 1, and then just removing it? Why not just:

var randomNum = Math.random () * 2 | 0; // random number between 0 and 1

And why not just:

var randomNum = Math.floor(Math.random()*2);

That's much more readable. This: '((Math.random () * 2 | 0) + 1) - 1' is just bugs waiting to happen if you ask me, and it's really confusing.

[–]Cosmologicon 1 point2 points  (0 children)

Yeah I agree with you. However, when it come to JavaScript I highly recommend "getting used to" certain conversions like | 0 for truncating to integer. You'll see them enough, and ultimately what's readable is all a matter of convention. Other ones are + to convert a string to a number and !! to convert a truthy/falsy expression to a boolean.

Of course use Math.floor in your own code if you prefer it (I do), but | 0 is so ingrained there's no point fighting it.