Home » Tutorials » JavaScript » JavaScript Random Unique Key Generator

JavaScript Random Unique Key Generator

JavaScript Random Unique Key Generator

Sometimes you may need to generate a unique key id at client side for your web application.

Following JavaScript snippet allows you to generate unique key randomly (look like GUID).

function guid() {
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

function s4() {
  return Math.floor((1 + Math.random()) * 0x10000)
    .toString(16)
    .substring(1);
}

document.getElementById('myID').addEventListener('click', function() {
  document.getElementById('myResult').value = guid();
})

Do not use this answer if you need compliant GUIDs.

Use these unique key at your own risk! No guarantee of their uniqueness is given or implied!


Android, iOS Development Tutorials