I'm trying to create globally-unique identifiers in JavaScript. I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc.
The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.
UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier), according to RFC 4122, are identifiers designed to provide certain uniqueness guarantees.
While it is possible to implement RFC-compliant UUIDs in a few lines of JavaScript code (e.g., see @broofa's answer, below) there are several common pitfalls:
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
", where x is one of [0-9, a-f] M is one of [1-5], and N is [8, 9, a, or b]Math.random
)Thus, developers writing code for production environments are encouraged to use a rigorous, well-maintained implementation such as the uuid module.
Actually, the RFC allows for UUIDs that are created from random numbers. You just have to twiddle a couple of bits to identify it as such. See section 4.4. Algorithms for Creating a UUID from Truly Random or Pseudo-Random Numbers: rfc-archive.org/getrfc.php?rfc=4122
This should not be the accepted answer. It does not actually answer the question - instead encouraging the import of 25,000 lines of code for something you can do with one line of code in any modern browser.
@AbhiBeckert the answer is from 2008 and for node.js projects it might be valid to choose a dependency more over project size
@Phil this is a "highly active question", which means it should have an excellent answer with a green tick. Unfortunately that's not the case. There is nothing wrong or incorrect with this answer (if there was, I'd edit the answer) - but another far better answer exists below and I think it should be at the top of the list. Also the question is specifically relating to javascript in a browser, not node.js.