w3resource

JavaScript: Function to create a UUID identifier

JavaScript Math: Exercise-23 with Solution

Write a JavaScript function to create a UUID identifier.

Note :
According to Wikipedia - A universally unique identifier (UUID) is an identifier standard used in software construction. A UUID is simply a 128-bit value. The meaning of each bit is defined by any of several variants. For human-readable display, many systems use a canonical format using hexadecimal text with inserted hyphen characters. For example : de305d54-75b4-431b-adb2-eb6b9e546014

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Write a JavaScript function to create a UUID</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function create_UUID(){
    var dt = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (dt + Math.random()*16)%16 | 0;
        dt = Math.floor(dt/16);
        return (c=='x' ? r :(r&0x3|0x8)).toString(16);
    });
    return uuid;
}

console.log(create_UUID());

Sample Output:

1fe35579-5ce7-46ec-89e0-7e7236700297

Flowchart:

Flowchart: JavaScript Math- Function to create a UUID identifier

Live Demo:

See the Pen javascript-math-exercise-23 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function that Convert Roman Numeral to Integer.
Next: Write a JavaScript function to round a number to a specified number of digits and strip extra zeros (if any).

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



JavaScript: Tips of the Day

Sort Number Arrays

JavaScript arrays come with a built-in sort method. This sort method converts the array elements into strings and performs a lexicographical sort on it by default. This can cause issues when sorting number arrays. Hence here is a simple solution to overcome this problem.

[0,10,4,9,123,54,1].sort((a,b) => a-b);
>>> [0, 1, 4, 9, 10, 54, 123]

You are providing a function to compare two elements in the number array to the sort method. This function helps us the receive the correct output.

Ref: https://bit.ly/3adlwNy