How to Generate Unique ID in JavaScript?
Using UUID module or Math.random method or Date.now method can generate a unique identifier (id) in JavaScript.
JavaScript generates a unique id Examples
Let’s see all ways example in HTML and JS:-
Using UUID library
To create a random UUID…
1. Install
1 |
npm install uuid |
2. Create a UUID (ES6 module syntax)
1 2 |
import { v4 as uuidv4 } from 'uuid'; uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' |
… or using CommonJS syntax:
1 2 |
const { v4: uuidv4 } = require('uuid'); uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' |
Read more: https://www.npmjs.com/package/uuid
Another solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html> <body> <script type="text/javascript"> 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()); </script> </body> </html> |
Output:

Math.random built-in function
This example will return a unique combination of numbers.
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html> <body> <script type="text/javascript"> var uid = Math.floor(Math.random() * 100) console.log(uid); </script> </body> </html> |
Output: 19
Date.now another JavaScript built-in function
Using this way will return number of miliseconds elapsed since January 1, 1970.
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html> <body> <script type="text/javascript"> var uid = Date.now() console.log(uid); </script> </body> </html> |
Output:

Do comment if you have any questions or suggestion on this topic.
Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version