

Update 06/03/10: Several people have expressed concern over how random the Math.random() method is. Update 1/22/10: includes an Math.uuid2 Math.uuidCompact – an alternate implementation for RFC4122v4 UUIDs designed to be as compact as possible, and Math.uuidFast() – an implementation designed for performance.

For example, one could use AJAX to fetch UUIDs generated by a site like, but that has it’s own set of issues. Regardless, this is a weakness that all javascript UUID generators will be subject to, unless they rely on an externally-provided unique value. It’s difficult to say for sure what the real-world uniqueness of these numbers ends up being, but I suspect it’s more than sufficient for most purposes. Generating truly random numbers is a notoriously tricky problem, solved in different (imperfect) ways across browser platforms and OSes. The uniqueness depends on how random the numbers generated by Math.random() are.

The practice is probably a little different. If every person on the planet filled up a terabyte hard drive with nothing but random UUIDs, there would only be a one in 7 trillion chance that two of the UUIDs would be the same. That makes for a staggering 5.3 x 10^^36 possible ids. Also, in javascript where Math.random() has to be used for UUID generation, the theoretical uniqueness of these ids is better than version 1 implementations since all 122 bits of field data are randomly generated. This avoids making an unfulfilled promise of universal uniqueness, while allowing for much simpler code. The more correct solution is to do what does – create “version 4” ids, which are defined as randomly generated (see RFC 4122, section 4.4). Using JavaScript to generate a version 1 UUID could be construed as misleading. But javascript doesn’t have an API for getting a guaranteed-unique anything – the best you can do is use Math.random() as a hack workaround which, strictly speaking, shouldn’t be used when uniqueness must be guaranteed. One common problem results from trying to produce “version 1” ids, which the RFC defines in a way that is supposed to guarantee the uniqueness of the ID. Googling around turns up several decent scripts, but all of these suffered from one drawback or another (IMHO). I put this together after discovering that nobody had published a really thin javascript implementation for generating UUIDs. For examples of the types of IDs it can generate, or to see performance data, check out the Test page. … as well as non-standard random IDs of arbitrary length and radix. The function supports RFC 4122-compliant UUIDs (or GUIDS), like this: Here’s a little JavaScript treat: is a function for generating different flavors of UUIDs in JavaScript.
