Ralph Holzmann

Web Development – jQuery, PHP, MySQL. In that order.

One Line Random Boolean in JavaScript December 28th, 2009

Happy Holidays everyone! I hope everyone enjoyed the holidays this year. I’m back to work today. I just wanted to post a quick snippet that I used in a jQuery plugin I’m developing. It’s nothing earth shattering, but I thought it was worth mentioning. It’s a true random boolean in JavaScript:

!Math.round(Math.random());

This creates a random number between zero and (almost) 1, then rounds it either up or down, then uses the negation operator twice once to convert it to a true boolean (if you pass it to the typeof function, it will return “boolean”).

Now back to work!

Edit: Josh Dean pointed out in the comments that only a single negation operator is needed in this case.

2 Comments Time: Relative | Actual

  1. Josh Dean said:

    Is the second negation really that necessary? If you check the typeof of the just a single negation, it still returns “boolean.”

    Is this a cross browser specific fix?

  2. Ralph said:

    Josh Dean, you’re right!

    My initial intuition was that the double negation (!!) takes any pseudo boolean (like the number zero or an empty string) and converts it into a true JavaScript boolean.

    However, in this case, since the value is inherently random to begin with, only one negation is needed to convert it to a true boolean. Thanks for the comment! I’ll update the post shortly.

Other stuff …

Tweets I write

Posts I write

Companies I currently develop for

Past development gigs

Things I use everyday

Ways to contact me