Lodash _.uniqueId() Method

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 6 Examples + 3 Try It
Util utilities

What You’ll Learn

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.

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.

📝 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)

⚡ Quick Reference

TaskCode patternResult
With prefix_.uniqueId("item_")item_1, then item_2, …
No prefix_.uniqueId()"1", "2", "3", …
DOM element idel.id = _.uniqueId("div_")Unique id on the page
In-memory row key{ id: _.uniqueId("row_"), … }Temp key before save
Secure random IDcrypto.randomUUID()Use instead for tokens/UUIDs
Sequential numbers_.times() + indexWhen you control the loop
Returns
String

Prefix + number

Counter
Global

Shared across prefixes

Scope
Runtime

Resets on reload

Production
UUID

For persisted IDs

🧰 Parameters

The single optional argument and what Lodash returns:

prefix Optional

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 value String

Concatenation of prefix + counter. The counter increases by 1 on every _.uniqueId() call anywhere in your app that shares the same Lodash instance.

_.uniqueId("x_") // "x_1"
_.uniqueId("y_") // "y_2"
counter state Internal

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 for Important

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.

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"
Try It Yourself

How It Works

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.

javascript
console.log(_.uniqueId());
// -> "3" (continues from prior examples)

console.log(_.uniqueId());
// -> "4"

How It Works

With no prefix, Lodash returns just the counter as a string. The counter never resets between prefixed and non-prefixed calls.

Example 3 — One counter for all prefixes

A common surprise: different prefixes still share the same number sequence.

javascript
console.log(_.uniqueId("alpha_"));
// -> "alpha_5"

console.log(_.uniqueId("beta_"));
// -> "beta_6"  — not "beta_1"

How It Works

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.

javascript
const panel = document.createElement("div");
panel.id = _.uniqueId("panel_");
panel.textContent = "Dynamic panel";

document.body.appendChild(panel);
// panel.id might be "panel_7"
Try It Yourself

How It Works

HTML requires unique id values on a page. _.uniqueId() is a quick way to avoid collisions when you append elements in a loop or event handler.

Example 5 — Temporary keys for an in-memory list

Before data is saved to a server, assign client-side keys so list UIs can track rows.

javascript
function addRow(label, rows) {
  rows.push({
    clientId: _.uniqueId("row_"),
    label
  });
  return rows;
}

const cart = [];
addRow("Notebook", cart);
addRow("Pen", cart);

console.log(cart);
// [
//   { clientId: "row_8", label: "Notebook" },
//   { clientId: "row_9", label: "Pen" }
// ]
Try It Yourself

How It Works

Replace clientId with the real server id after save. Do not use _.uniqueId() inside React render as a key—keys must stay stable across re-renders.

🚀 Beyond the Basics

When Lodash is not the right tool and what to use instead.

Example 6 — Modern alternatives

For unpredictable, globally unique strings, native and third-party UUID helpers are a better fit.

javascript
// Lodash — predictable, incrementing (good for temp labels)
const temp = _.uniqueId("draft_");

// Browser — random UUID v4 (good for tokens, file names)
const secure = crypto.randomUUID();
// e.g. "f47ac10b-58cc-4372-a567-0e02b2c3d479"

// When you control the loop, _.times also works:
const numbered = _.times(3, (i) => `item_${i + 1}`);
// ["item_1", "item_2", "item_3"]

When to prefer Lodash

Reach for _.uniqueId() in quick scripts, demos, and DOM utilities where readability and zero setup matter more than cryptographic strength.

🧠 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).

📝 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().

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.

💡 Best Practices

✅ Do

  • 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

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
🔢 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.

Practice _.uniqueId() in the Live Editor

Open the Try It editor, run the examples, and experiment with your own prefixes.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful