Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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));
like image 760
arjun kr Avatar asked Aug 18 '26 22:08

arjun kr


1 Answers

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));
like image 147
Nina Scholz Avatar answered Aug 20 '26 12:08

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!