Create string letter and string length

I would like to create a string starting with a letter and the length of the 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;
  
}
      

Run codeHide result


+3


source to share


1 answer


I don’t know how much better this is from a performance standpoint, as some engines optimize the code and others don’t. However, it is readable, by the javascript programmer.

You can create an array with a size len + 1

and then join it with a letter.



For this we will use the array constructor, where we can determine the size of the array and Array.join

to join the array with the data letter

.

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

      

+4


source







All Articles