How to Generate Unique IDs in JavaScript
How many?
How to Generate Unique IDs in JavaScript
1. Using the Current Time
Generate a unique ID based on the current time. Keep in mind, this might not be completely unique if you generate many IDs quickly.
const uniqueId = Date.now().toString();
console.log(uniqueId);
2. Using a Random Number
This method creates an ID using a random number. Simple, but not perfect for every use case.
const uniqueId = Math.random().toString(36).substring(2, 15);
console.log(uniqueId);
3. Using crypto.randomUUID()
In newer browsers and Node.js, you can use this built-in function for a truly unique ID.
const uniqueId = crypto.randomUUID();
console.log(uniqueId);
4. Using a Library
For an easy and reliable method, use a library like uuid
.
Install the library for your project:
npm install uuid
Generate a UUID:
import { v4 as uuidv4 } from 'uuid';
const uniqueId = uuidv4();
console.log(uniqueId);
These are various ways to generate unique IDs in JavaScript, ranging from simple to more sophisticated methods.