How to create a random UUID in JavaScript

The UUID, a universally unique identifier, can be created using the randomUUID method of the global property crypto. This method will generate the v4 UUID using a cryptographically secure random number generator.

Syntax

crypto.randomUUID()

Arguments

This method doesn’t take any argument.

Return value

This method returns a string value that contains a randomly generated v4 UUID. The returned string will have 36 characters.

Code

The below code demonstrates how to generate a random UUID in JavaScript.

Console
Generate a random UUID in JavaScript

Explanation

  • Lines 6-9: We’ve used the crypto.randomUUID method to generate the random v4 UUID.

Note: The v4 UUID will have the character 4 in the first position of the third section of the UUID. Ex: c7d03fd6-c898-4b79-83c3-e13fe4f41b4c in this UUID after the second hyphen the character 4 will be present.