generateUUID
Generates a random UUID (version 4).
1/**
2 * Generates a random UUID (version 4).
3 *
4 * @returns A UUID v4 string in the format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx.
5 */
6export function generateUUID(): string {
7 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, char => {
8 const rand = Math.random() * 16 | 0;
9 const value = char === 'x' ? rand : (rand & 0x3 | 0x8);
10 return value.toString(16);
11 });
12}
Conforms to UUID v4 Format
Ensures the correct structure with fixed version and variant bits, complying with RFC 4122.
No External Dependencies
Works entirely with built-in JavaScript features, making it portable and lightweight.
Sufficient Randomness for Most Use Cases
Uses
Math.random()
to generate values with enough entropy for non-cryptographic purposes.Deterministic Structure
Hardcodes the format string, making version (
4
) and variant (8–b
) bits predictable and standards-compliant.
Tests | Examples
1test('generateUUID - returns a string', () => {
2 const uuid = generateUUID();
3 expect(typeof uuid).toBe('string');
4});
5
6test('generateUUID - has correct format and length', () => {
7 const uuid = generateUUID();
8 const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
9 expect(uuid.length).toBe(36);
10 expect(uuidRegex.test(uuid)).toBe(true);
11});
12
13test('generateUUID - generates different values', () => {
14 const uuid1 = generateUUID();
15 const uuid2 = generateUUID();
16 expect(uuid1).not.toBe(uuid2);
17});
Common Use Cases
Client-Side ID Generation
Assign unique identifiers to objects or elements in frontend applications.
Temporary Resource Keys
Use as short-lived identifiers for uploads, user sessions, or tracking actions.
Testing and Mock Data
Generate fake UUIDs in unit tests, mock APIs, or data factories.
Offline Data Storage
Create local record keys in
IndexedDB
,localStorage
, or caches before syncing with a server.