JS UUIDv4 Generator

The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination. […] Anyone can create a UUID and use it to identify something with reasonable confidence that the same identifier will never be unintentionally created by anyone to identify something else. Information labeled with UUIDs can therefore be later combined into a single database without needing to resolve identifier (ID) conflicts.

Wikipedia, the free encyclopedia

function UUIDv4() {
	var rand = new Uint8Array(16);
	crypto.getRandomValues(rand);
	rand[6] = (rand[6] & 0x0f) | 0x40;
	rand[8] = (rand[8] & 0x3f) | 0x80;
	var i = 0;
	return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/xx/g, () => ('0' + rand[i++].toString(16)).slice(-2));
}

Keeping to only pre-ES6 code the arrow function can be replaced with a function block, leaving, a more verbose:

function UUIDv4() {
	var rand = new Uint8Array(16);
	crypto.getRandomValues(rand);
	rand[6] = (rand[6] & 0x0f) | 0x40;
	rand[8] = (rand[8] & 0x3f) | 0x80;
	var i = 0;
	return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/xx/g, function () { return ('0' + rand[i++].toString(16)).slice(-2); });
}

When minified the ES6 version is only 184 bytes.

function UUIDv4(){var r=crypto.getRandomValues(new Uint8Array(16)),i=0;r[6]=r[6]&15|64;r[8]=r[8]&63|128;return'0000-00-00-00-000000'.replace(/0/g,z=>(z+r[i++].toString(16)).slice(-2))}

The ES6 version can be made even smaller by replacing the function body with an arrow function, leaving only 171 bytes.

UUIDv4=(r,i)=>(r=crypto.getRandomValues(new Uint8Array(16)),i=0,r[6]=r[6]&15|64,r[8]=r[8]&63|128,'0000-00-00-00-000000'.replace(/0/g,z=>(z+r[i++].toString(16)).slice(-2)))

Without the function assignment it comes to only 164 bytes.

(r,i)=>(r=crypto.getRandomValues(new Uint8Array(16)),i=0,r[6]=r[6]&15|64,r[8]=r[8]&63|128,'0000-00-00-00-000000'.replace(/0/g,z=>(z+r[i++].toString(16)).slice(-2)))

The pre-ES6 version, once minified, is only 200 bytes.

function UUIDv4(){var r=crypto.getRandomValues(new Uint8Array(16)),i=0;r[6]=r[6]&15|64;r[8]=r[8]&63|128;return'0000-00-00-00-000000'.replace(/0/g,function(z){return(z+r[i++].toString(16)).slice(-2)})}

This implementation relies upon crypto.getRandomValues to generate random numbers for the UUID so they have uniform distribution and are cryptographically secure. You will need a polyfill for crypto.getRandomValues to use this in older browsers, unfortunately the more widely supported Math.random is completely unsuitable for this task.