Generating Unique Identifiers in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to generate a UUID in a browser using JavaScript. A UUID (Universally Unique Identifier) is a 128-bit value used to identify resources in a system in a way that is both unique and universal. By the end of this lab, you will have a clear understanding of how to generate a compliant UUID that can be used in your web applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28686{{"`Generating Unique Identifiers in JavaScript`"}} javascript/data_types -.-> lab-28686{{"`Generating Unique Identifiers in JavaScript`"}} javascript/arith_ops -.-> lab-28686{{"`Generating Unique Identifiers in JavaScript`"}} javascript/comp_ops -.-> lab-28686{{"`Generating Unique Identifiers in JavaScript`"}} end

Generate UUID in Browser

To generate a UUID compliant with RFC4122 version 4 in a browser, follow these steps:

  1. Open the Terminal/SSH and type node.
  2. Use the Crypto.getRandomValues() method to generate a UUID.
  3. Convert the UUID to a hexadecimal string using the Number.prototype.toString() method.
  4. Implement the following code:
const UUIDGeneratorBrowser = () =>
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  );
  1. Call the UUIDGeneratorBrowser() function to generate a UUID. For example, UUIDGeneratorBrowser() would return '7982fcfe-5721-4632-bede-6000885be57d'.

Summary

Congratulations! You have completed the Generate UUID (Browser) lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like