How to generate a random ID in JavaScript

February 22, 2020

I’m sure this is posted in a ton of places already but I thought I would share a method I sometimes use to generate random strings of (numbers + letters) with javascript. This function returns the first 6 characters of a randomly generated string. Passing 36 to the toString method tells it to return numbers 0-9 and every letter in the alphabet, you can adjust the 6 in the substr method if you want a longer or shorter ID.

const id = function() {
  return Math.random()
    .substr(2, 6);

Written by Matt Gregg, a UI engineer who lives and works in Minneapolis, MN

Have something to say about this post? Tweet at me