Concatenate the result of a repeated n times function

Let's assume that you have the following function:

javascript
const randomChar = () => {
    
    let alphabet = 'abcdefghijklmnopqrstuvwxyz';
    
    return alphabet[~~(Math.random() * alphabet.length)];
    
}

Now, you want repeat the execution of a JavaScript function n times and concatenate it with different results.

If n is small, let's say n < 5:

javascript
// If the string is short, you could write the concatenation manually
let x_4 = randomChar() + randomChar() + randomChar() + randomChar();

console.log(res);
// gerx

If n is large, let's say n >= 5:

javascript
// If you want a random string of e.g. n = 50 chars
// The first solution would be a for loop
for(var i = 0, x_50 = ''; i < 50; i ++){
    
    x_50 += randomChar(); 
    
}

console.log(x_50);
// gtuwjjxqgmpbmviluprsnbvfawrrmeeanwwvgecrgcwijomsgq

If the previous solution seems too long, consider the following alternative:

javascript
// You can use the reduce function with an array of size 50
// The previous solution is quicker, but this one is shorter
let x_50 = Array(50).fill().reduce(acc => acc + randomChar(), '');  

console.log(x_50);
// sowdyufypborbgzzlmtkzxfcjfdviavuoqyglgnjwufsfjaene

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.