Error concatenating strings in a for loop

Hello, I'm trying to generate a random string of length 12
let id = '';

for(let i = 0; i < 12; i++) {
let randNum = Math.floor(Math.random() * (128 - 21) + 21);
let char = String.fromCharCode(randNum);
id += char;
}
let id = '';

for(let i = 0; i < 12; i++) {
let randNum = Math.floor(Math.random() * (128 - 21) + 21);
let char = String.fromCharCode(randNum);
id += char;
}
What I'm trying to do is, first, generate a random character, using the ASCII table starting at 21 till 127. Then with the String.fromCharCode, I get the character equivalent of the number generated. The idea is that, I have an empty string and I use the += operator to concatenate whatever char I get from the loop, easy peasy lemon squeezy, nothing out of the ordinary, BUT, and this may be a conceptual mistake, when I run this code I get a reference error saying that id has already BEEN DECLARED but I don't see myself redeclaring it so I don't understand. Also, I've tried with the .concat method and it still gives the same result. Using const doesn't work either.
6 Replies
David
David2y ago
Issue found, id was defined else where when I opened my console
David
David2y ago
MarkBoots
MarkBoots2y ago
I was already confused because it worked for me
David
David2y ago
Guess using "id" or "char" are too common
MarkBoots
MarkBoots2y ago
make it a function so you wont run into that problem. Also you can pass different arguments. for example length Something like this
function randomId(length=12){
let idString = ""
for(let i = 0; i < length; i++){
const randomCharCode = Math.floor(Math.random() * (128 - 21) + 21);
idString += String.fromCharCode(randomCharCode)
}
return idString;
}

console.log(randomId()); //default length 12
console.log(randomId(8)); //length 8
function randomId(length=12){
let idString = ""
for(let i = 0; i < length; i++){
const randomCharCode = Math.floor(Math.random() * (128 - 21) + 21);
idString += String.fromCharCode(randomCharCode)
}
return idString;
}

console.log(randomId()); //default length 12
console.log(randomId(8)); //length 8
David
David2y ago
Thanks!