Skip to content
Related Articles

Related Articles

Underscore.js _.uniqueId() Function

View Discussion
Improve Article
Save Article
  • Last Updated : 15 Oct, 2020

Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invoke, etc even without using any built-in objects.

The _.uniqueId() function is an inbuilt function in Underscore.js library of JavaScript which is used to generate a globally unique id for the client-side models or the DOM elements which requires one. When a prefix is passed as an argument to this method, the id generated will be appended to it.

Syntax:

_.uniqueId( prefix )

Parameters: It accepts a single parameter as mentioned above and described below:

  • prefix: It is the prefix that would be appended to the id It is am optional parameter.

Return Value: This method returns a globally unique id.

Example 1:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <script type="text/javascript">
  
        // Using _.uniqueId() method 
        // with its parameter
        console.log(_.uniqueId('gfG_'));
        console.log(_.uniqueId('Geeks_'));
        console.log(_.uniqueId('CS_'));
    </script>
</body>
  
</html>


Output:

gfG_1
Geeks_2
CS_3

Example 2:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <script type="text/javascript">
  
        // Using a loop
        for (i = 3; i < 100; i *= 2) {
  
            // Calling uniqueId method
            // without any parameter   
            console.log(_.uniqueId());
        }
    </script>
</body>
  
</html>


Output:

1
2
3
4
5
6

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!