Open In App

Lodash _.uniqueId() Method

Last Updated : 18 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.uniqueId() method is used to create a unique ID for an element each time. This method will work for the purpose of assigning a unique ID for most use cases, but not with complex projects that require a unique ID even if the project restarts. 

Syntax:

_.uniqueId([prefix = ''])

Parameters:

  • prefix is the value to prefix the ID with.

Return Value:

This method returns the string’s unique ID.

Example 1: In this example, we are printing the unique id in the console by using the _.uniqueId() method.

Javascript




// Requiring the lodash library 
const _ = require("lodash");
 
// Use of _.uniqueId() 
// Method without the prefix
let gfg = _.uniqueId();
 
// Printing the output 
console.log(gfg);


Output:

1

Example 2: In this example, we are printing the unique id in the console by using the _.uniqueId() method having ‘gfg’ as a prefix.

Javascript




// Requiring the lodash library 
const _ = require("lodash");
 
// Use of _.uniqueId() 
// Method with prefix
let ans = _.uniqueId("gfg_");
 
// Printing the output 
console.log(ans);
 
let ans1 = _.uniqueId("gfg_");
 
// Printing the output 
console.log(ans1);


Output:

gfg_1
gfg_2

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads