There are several ways to generate unique IDs in JavaScript. One commonly used method utilizes the crypto API, a native feature that provides cryptographic functionality for secure operations like hashing, encryption, and decryption. We’ll explore the randomUUID method from the Crypto API to generate unique IDs.
Example
const uniqueId = crypto.randomUUID();
// (This will return a unique value on every call)
Output
487a3de3-4243-45e1-91d1-1eb5aaba5405
Let’s apply this method to create a list of students, each with a unique ID.
const students = [
{ id: crypto.randomUUID(), name: "Jack", class: 6, section: "A" },
{ id: crypto.randomUUID(), name: "Tom", class: 6, section: "A" },
];
Output
[
{
id: "f9189550-ae48-436d-bb49-d43bcf682fdd",
name: "Jack",
class: 6,
section: "A",
},
{
id: "60632624-98cb-46e1-ae9c-8dd2e7eb1614",
name: "Tom",
class: 6,
section: "A",
},
];
If you find this helpfull please share with your network ✅.
Happy Coding 🙌 !