Repeating a string without using a for loop in javascript

Sep 27, 2011 No Comments by Mahdi Pedram

Even though it is not recommended to use Array constructor. but sometimes we can get some usage of it.
One good example would be repeating a string without using a for loop.

in this example we are creating an empty array with default undefined values.
( when you specify a size for an array, without setting the values in it, it will have undefined as a default value for all the indexes)

by joining the new array with our string we can repeat the string as many time as we want.
this is more efficient smaller and cleaner.

 
 
function repeatStr(str,count){
  return new Array(count+1).join(str);
}
 
var str = "MyString";
var repeatedStr = repeatStr(str,3); // returns MyStringMyStringMyString
 

I hope you found this article helpful

javascript

About the author

I'm Web Developer , I spent most of my time on programming web applications ,I'm both Front-end , Back-end Developer . Coding is part of my life , I don't do programming for life , I am alive to Code
No Responses to “Repeating a string without using a for loop in javascript”

Leave a Reply