Skip to main content


Showing posts from December, 2014

JavaScript: Next Unique ID Function

Unique ID generation is used in JavaScript application in many places. For example giving the unique id to DOM element or may be using it to some data structure for storing in memory, where it can be use latter. Most of the implementation I see is just defining the integer and increasing it on every call. But it is potentially candidate to integer overflow issue, which can cause errors in many edge case scenario. var nextUid = (function(){ var idCounter = 0; //integer counter return function (prefix) { //counter increment on every call, and it can run into integer overflow issue var id = ++idCounter; return String(prefix == null ? '' : prefix) + id; } })(); When I was reading through AngularJS source code, found this really good implementation of unique ID generation. Below is the extracted and updated version of the same, so you can use it independently. /** A consistent way of creating unique IDs in angular. The ID is a seque