One Line Random Boolean in JavaScript

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.

This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

2 Responses to One Line Random Boolean in JavaScript

  1. Josh Dean says:

    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 says:

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>