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.
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?
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.