How to generate a unique random ID using JavaScript?

In JavaScript we can generate a unique ID in many different ways. If we can consider ES6 then using crypto API we can generate a unique ID. Following is the function definition of generating a unique ID in JavaScript.

Function definition:

function getUniqueKey(){
    return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
    );
};

Function call:

getUniqueKey()

Function output:

"8b3f8c2a-7269-4390-9791-da792aa56eb6"
Share