Update: From the comments below it looks like I arrived at the same solution as someone else had  come up with earlier. Recommend you check out the Broofa.com code as they have done more work on making it more performant and robust.




A while ago I needed a quick and simple way to generate a GUID in a JavaScript project but most of the examples that I could find were either slow, cumbersome or didn’t always pass GUIDs that would pass verification, so I had an attempt at writing my own that had to be performant, small and robust enough to use in a real world environment at scale.


Well, after generating 50 million GUIDs across all the mainstream browsers (and some pretty obscure ones!) in my other logging system (an internal project, not jsErrLog – though it’s used there as well) I’m happy that it’s behaving well enough to share so with no further ado…


function guid() { // http://www.ietf.org/rfc/rfc4122.txt section 4.4

                return 'aaaaaaaa-aaaa-4aaa-baaa-aaaaaaaaaaaa'.replace(/[ab]/g, function(ch) {

                                var digit = Math.random()*16|0, newch = ch == 'a' ? digit : (digit&0x3|0x8);

                                return newch.toString(16);




Regular expressions, nested functions and logical operators… probably the most I’ve every crammed into that few characters though if you’re really obsessive you can crunch it down even further to one line at the cost of readability:


guid=function(){return"aaaaaaaa-aaaa-4aaa-baaa-aaaaaaaaaaaa".replace(/[ab]/g,function(ch){var a=Math.random()*16|0;return(ch=="a"?a:a&3|8).toString(16)}).toUpperCase()};