By the end of this tutorial, you’ll know when and how to use Lodash’s _.uniqueId() to create quick, incrementing string identifiers in JavaScript.
01
Core Syntax
Call _.uniqueId([prefix]) with an optional string prefix.
02
Global Counter
Understand that one shared counter drives every call.
03
DOM & UI Labels
Assign id attributes and temporary client-side keys.
04
Prefix Patterns
Use descriptive prefixes like user_ or row_ for clarity.
05
Know the Limits
Not for databases, security tokens, or cross-session uniqueness.
06
Modern Alternatives
Compare with crypto.randomUUID() and when to switch.
Fundamentals
What Is _.uniqueId()?
_.uniqueId() is a Lodash utility that returns a string identifier built from an optional prefix plus an auto-incrementing number. Lodash keeps a single module-level counter; every call advances it by one, so you never get the same ID twice in the same runtime.
💡
Beginner tip
Think of _.uniqueId('task_') as a quick label printer: first call gives task_1, next gives task_2, and so on. It is handy for temporary names—not for permanent database IDs.
You will see this in tutorials, prototypes, and DOM scripts where you need a unique id or key without pulling in a UUID library. For production persistence or security-sensitive identifiers, prefer purpose-built solutions instead.
Foundation
📝 Syntax
The signature is minimal—an optional prefix string:
javascript
_.uniqueId([prefix])
Syntax Rules
prefix — optional string prepended to the number (defaults to empty).
Return value — always a string, e.g. "user_42" or "7".
Shared counter — all prefixes use the same incrementing number sequence.
Process scope — uniqueness lasts for the current page/app session, not forever.
Not cryptographic — predictable and guessable; do not use for secrets.
javascript
import uniqueId from "lodash/uniqueId";
const id = uniqueId("user_");
// -> "user_1" (first call in this runtime)
The single optional argument and what Lodash returns:
prefixOptional
A string placed before the incrementing number. Omit it to get bare numbers as strings ("1", "2"). Use short, meaningful prefixes for debugging and DOM ids.
_.uniqueId("btn_")
_.uniqueId()
return valueString
Concatenation of prefix + counter. The counter increases by 1 on every _.uniqueId() call anywhere in your app that shares the same Lodash instance.
Lodash stores the counter on its internal namespace. You cannot reset it through the public API—reload the page or create a fresh Lodash context with _.runInContext() if you need a clean slate.
// one shared sequence
not suitable forImportant
Database primary keys, API auth tokens, file names that must never collide across users, or React list keys that must stay stable between renders.
// use UUID / server id instead
Lodash converts the numeric part to a string and concatenates it with your prefix. There is no separator added automatically—you include underscores or dashes in the prefix yourself.
Hands-On
Examples Gallery
Practical _.uniqueId() patterns with copy-ready code, sample output, and interactive Try It Yourself labs.
📚 Getting Started
Generate your first prefixed IDs and see how the counter advances.
Example 1 — Basic ID with a prefix
Create a readable identifier by passing a prefix string. Each call returns the next number in the sequence.
javascript
const first = _.uniqueId("user_");
const second = _.uniqueId("user_");
console.log(first);
// -> "user_1"
console.log(second);
// -> "user_2"
Lodash appends the current counter value to your prefix and then increments the counter. The prefix is only for readability—the number always comes from the shared sequence.
Example 2 — IDs without a prefix
Skip the prefix when you only need simple numeric strings.
If you need independent counters per prefix, maintain your own map of counts or use a different ID strategy. Lodash intentionally keeps one global sequence for simplicity.
📈 Practical Patterns
Real-world places where lightweight incrementing IDs help in the browser.
Example 4 — Assign a DOM element id
When creating elements dynamically, give each one a unique id for styling, testing, or document.getElementById.
Reach for _.uniqueId() in quick scripts, demos, and DOM utilities where readability and zero setup matter more than cryptographic strength.
Compare
📋 _.uniqueId vs related approaches
Topic
_.uniqueId
crypto.randomUUID()
_.times + index
Server / DB id
Format
prefix + number
UUID v4 string
You define pattern
Auto-increment / UUID
Predictable
Yes
No
Yes
Varies
Cross-session unique
No
Very likely
No
Yes
Setup
Lodash only
Modern browsers
Lodash only
Backend required
Best use
Temp DOM / UI labels
Tokens, files, APIs
Batch from a loop
Persisted records
🧠 How _.uniqueId() Works
1
Read optional prefix
Lodash uses the string you pass, or "" if omitted.
Input
2
Increment global counter
An internal idCounter (or equivalent) bumps by 1 on every call.
State
3
Concatenate and return
Prefix and counter are joined into one string—no extra separator is inserted.
Output
=
🏷️
Unique string ready to use
Assign to DOM ids, in-memory objects, or log labels—unique until the runtime ends or counter wraps (practically never in normal apps).
Important
📝 Notes
IDs are unique within the current Lodash instance, not across browsers or servers.
All prefixes share one counter—_.uniqueId("a_") then _.uniqueId("b_") yields b_2, not b_1.
The counter resets on full page reload; do not rely on IDs surviving refresh.
Not suitable for database primary keys, auth tokens, or security-sensitive identifiers.
Do not call _.uniqueId() on every React render for key props—use stable ids from your data.
For random UUIDs in modern browsers, prefer crypto.randomUUID().
Wrap Up
Conclusion
_.uniqueId() is a small but handy Lodash helper: pass an optional prefix, get back the next incrementing string, and move on. It shines for DOM ids, prototypes, and temporary client-side labels where you need uniqueness without ceremony.
Keep its limits in mind—predictable numbers, process-scoped uniqueness, and a shared counter. When you need real UUIDs or persisted record ids, step up to crypto.randomUUID() or server-generated values.
Use descriptive prefixes (panel_, row_) so IDs are self-documenting
Reserve _.uniqueId() for temporary, in-browser identifiers
Pair with _.times() when generating many labeled items in a loop you control
Replace client-side ids with server ids after a successful save
Use crypto.randomUUID() when unpredictability matters
❌ Don’t
Store _.uniqueId() values as permanent database primary keys
Assume each prefix starts counting from 1
Generate new React key values on every render with _.uniqueId()
Use it for session tokens, passwords, or API secrets
Expect the same id after a page refresh or in another user’s browser
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about _.uniqueId()
Use these points whenever you need a quick string identifier in JavaScript.
5
Core concepts
🏷️01
Prefix + number
Returns a readable string.
Basics
🔢02
Global counter
All prefixes share it.
Gotcha
🌐03
Runtime scope
Resets on reload.
Limits
🛠04
DOM ids
Great for dynamic elements.
Use case
🔐05
Use UUIDs
For real persistence.
Production
❓ Frequently Asked Questions
_.uniqueId() returns a string made of an optional prefix plus an incrementing number. Each call bumps a shared Lodash counter, so IDs are unique within the current JavaScript process.
No. _.uniqueId() with no arguments returns "1", then "2", "3", and so on. With a prefix like "user_", you get "user_1", "user_2", etc.
No. Lodash uses one global counter for all calls. After _.uniqueId("a_") returns "a_1", the next _.uniqueId("b_") is "b_2", not "b_1".
No. It is meant for lightweight client-side or in-memory labels. Use database auto-increment, UUIDs, or another server-generated ID for persisted records.
The counter resets when your app reloads. IDs are not stable across sessions, tabs, or servers—only within the current runtime.
Use crypto.randomUUID() (or a library like nanoid) when you need hard-to-guess, globally unique strings—for API tokens, file names, or distributed systems. Use _.uniqueId() for quick temporary labels in the browser.
Did you know?
_.uniqueId uses a single shared counter for every prefix in your app. That is why _.uniqueId("a_") followed by _.uniqueId("b_") returns b_2, not b_1. For unpredictable IDs see crypto.randomUUID() in the MDN docs.