How to generate a unique id in JavaScript

PHP makes it pretty easy to generate a unique it with the uniqid() command. JavaScript doesn’t have that command, but using the getTime() function of the Date object we can do almost the same thing.

JavaScript:
  1. function uniqid()
  2.     {
  3.     var newDate = new Date;
  4.     return newDate.getTime();
  5.     }

The function returns the number of milliseconds since January 1, 1970.

Question, Comments...

Do you have more questions. Please either leave a comment below or join us in our new forum.

2 Responses to “How to generate a unique id in JavaScript”

  1. [...] Forums, Blogs, Wikis News on forums, blogs, wikis, cms, etc « How to generate a unique id in JavaScript [...]

  2. Found a problem if you’re using this to generate unique IDs in rapid succession. It’s possible that two IDs can be generated within the same millisecond and therefore will have the same “unique” ID. Instead try this technique that increments a variable to keep the ID unique.

Leave a Reply