How about this compact little trick?
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var stringLength = 5; var randomString = Array.apply(null, new Array(stringLength)).map(function pickRandom() { return possible[Math.floor(Math.random() * possible.length)]; } var randomString = Array.apply(null, Array(stringLength)).map(pickRandom).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; constvar randomString = Array.from({ length: stringLength }, () => { return possible[Math.floor(Math.random() * possible.length)]; }pickRandom).join('');