How about this compact little trick?
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var stringLength = 5; var randomString = Array.apply(null, new Array(stringLength)).map(function () { return possible[Math.floor(Math.random() * possible.length)]; }).join(''); You need the Array.apply there to trick the empty array into being an array of undefineds.
If you're coding for ES2015, then building the array is a little simpler:
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const stringLength = 5; const randomString = Array.from({ length: stringLength }, () => { return possible[Math.floor(Math.random() * possible.length)]; }).join('');