I want to create a random string (token) which can be used to identify a user whilst avoiding any potential conflicts with any other users\' tokens.
What I was thinking
I use an approach similar to Kareem's, but with fewer function calls and built-in array operations for a big boost in performance.
According to a performance test, this method also outperforms the accepted answer by a small margin. Moreover it provides a parameter n to generate any size token length from a white list of acceptable characters. It's flexible and performs well.
function generateToken(n) {
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var token = '';
for(var i = 0; i < n; i++) {
token += chars[Math.floor(Math.random() * chars.length)];
}
return token;
}