Creating Unique Strings (UUIDs) in JavaScript

This article can be read in about 3 minutes.
PR

The purpose 

Creating Unique Strings (UUIDs) in JavaScript.

Example

I’ll give the class a unique string (UUID) to use for instance verification instead of pointers.

PR

Implementation


Here’s the translation:

You can create a unique string (UUID) with the following single line of code (it returns a different string with each call):

const uuid = self.crypto.randomUUID();

The returned value will be in the format of 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' (e.g., 'd6436922-c138-4ef3-bab6-5de2546f847e').

I read the documentation, but I couldn’t understand how uniqueness is maintained.

Although the probability is low, it’s not guaranteed that the same value won’t be generated.

If necessary, please implement a process to check if the generated UUID conflicts with any already issued UUIDs.

Implementation Examples

For examples where a class needs a unique string (UUID) to identify instances instead of using pointers, the following implementation should be sufficient.

class tool {
    #uid;
    constructor(){
        this.#uid = self.crypto.randomUUID();
    }
    get uid(){return this.#uid}
}
PR

Reference

Crypto: randomUUID() メソッド - Web API | MDN
randomUUID() は Crypto インターフェイスのメソッドで、暗号強度の強い乱数生成器を用いて v4 UUID を生成するのに用いられます。

comment

Copied title and URL