arjun kr
arjun kr

Reputation: 973

Why Array(1).join('str') output empty?

Why below block of code not output string ?

I was expecting it should display abc when we pass num=1.

What I am missing here ?

function repeatStringNumTimes(str, num) {
  return Array(num).join(str);
}
console.log(repeatStringNumTimes("abc", 1));

Upvotes: 2

Views: 121

Answers (3)

Denialos
Denialos

Reputation: 1006

If you only need a string to be repeated n times, use ES6's String.repeat, like so:

'myString'.repeat(repeatTimes);

Or an array-based solution (not recommended for your problem, though):

new Array(repeatTimes).fill('myString').join('');

If you need ES5 solution, use lodash fn repeat:

_.repeat('abc', 2);

Upvotes: 2

Chris Lam
Chris Lam

Reputation: 3614

The correct way should be

str.repeat(num)

Upvotes: -2

Nina Scholz
Nina Scholz

Reputation: 386654

You need at least two elements for Array#join with a separator, because one element is just converted to a string and it does not need any glue.

function repeatStringNumTimes(str, num) {
    return Array(num + 1).join(str);
}
console.log(repeatStringNumTimes("abc", 1));

Upvotes: 9

Related Questions