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
npm install uuid
2. Create a UUID (ES6 module syntax)
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
… or using Common JS syntax:
<!-- wp:paragraph -->
<p>… or using CommonJS syntax:</p>
<!-- /wp:paragraph -->
Read more: https://www.npmjs.com/package/uuid
Another solution
<!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.
<script type="text/javascript">
var uid = Math.floor(Math.random() * 100)
console.log(uid);
</script>
Output: 19
Date.now another JavaScript built-in function
Using this way will return number of miliseconds elapsed since January 1, 1970.
<!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: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version