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>
  <meta charset="utf-8">
  <title>Write a JavaScript function to create a UUID</title>


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;


Sample Output:



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.

Share this Tutorial / Exercise on : Facebook and Twitter

JavaScript: Tips of the Day

var keyword

var num = 8;
var num = 10;


With the var keyword, you can declare multiple variables with the same name. The variable will then hold the latest value.
You cannot do this with let or const since they're block-scoped.

Ref: https://bit.ly/323Y0P6