Open In App

Underscore.js _.uniqueId() Function

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:



Return Value: This method returns a globally unique id.

Example 1:




<!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:




<!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

Article Tags :