vcom6g
Last Updated: March 24, 2016
·
13.42K
· aalaap
Aalaap filter 512

Quick coin flip heads/tails function in JavaScript

If you need a simple choice between one thing or another, here's a function that generates a random number between 0 and 1 and returns it.

function coinFlip() {
    return Math.floor(Math.random() * 2);
}

If you prefer true or false values...

function coinFlip() {
    return (Math.floor(Math.random() * 2) == 0);
}

Or if you really want to stick to the whole heads/tails thing..

function coinFlip() {
    return (Math.floor(Math.random() * 2) == 0) ? 'heads' : 'tails';
}
Say Thanks
Respond

3 Responses
Add your response

8606
052ee0d106425f379a2a6d9f0c8187f1

=== 0

over 1 year ago ·
8679
Aalaap filter 512

That wouldn't hurt, but, given that it's always going to be a number between 0 and 2, is a strict equal operator really neccessary?

over 1 year ago ·
11040
57e15d6acbd5f46c300a83b5e61db1de

You should always use === and !==, never the "evil twins" (REF: http://www.amazon.com/dp/0596517742 JavaScript: The Good Parts)

over 1 year ago ·