09 April 2019

Creating an unique id


Intro

Sometimes you need a unique, randomly generated ID. It could be used to identify an input from a form. A randomly created number, wouldn't do the trick.
With a small trick we can create a number-char combination, that is unlikely to be created twice.

Code

var hashValue = Math.random().toString(16).slice(2);
// hashValue contains the random string now

Explanation

Math.random()
This creates a random number between 0 and 1.
A possible result could be: 0.95043825801676

Math.random().toString(16)
This converts the generated decimal number (base 10) to a hexadecimal number (base 16). So you get values, where each digit is between 0 and F (0123456789ABCDEF).
0.95043825801676 in hexadecimal would be 0.f34febf30c97f8.

Math.random().toString(16).slice(2)
To get rid of everything in front of the decimal point, we just cut off the first 2 chars (to be exact, we tell JS to start the string at position 2).
The result would be: f34febf30c97f8

Amazon