puppeteer701
puppeteer701

Reputation: 1285

Create string of Letter and length of a string

I would like to create a string, from a letter and length of a string. This is what I currently have, but is there a better way to do this?

function generate(letter, len) {
   var str = '';
   for (var i=0; i<len; i++) {
     str+=letter;
   }
  
   return str;
  
}

Upvotes: 3

Views: 54

Answers (1)

Amit Joki
Amit Joki

Reputation: 59232

Don't know if this is better in terms of performance as some engines optimize the code while others do not. However it's readable, to a javascript programmer.

You can create an array with size len + 1 and then join it by the letter.

For this, we will make use of array constructor, where we can define the size of the array and Array.join to join the array with the given letter.

function generate(letter, len) {
    return new Array(len + 1).join(letter); 
}

Upvotes: 4

Related Questions