I have come across an interesting piece of code:
function repeat(str,x) {
return Array(x+1).join(str);
}
repeat("wow", 2);
The outcome of this is a string "wowwow"
. However, I have no idea what this Array(x+1)
is actually doing. And very interesting thing is that if I just use Array(x)
it prints the str
only once and not twice as expected.
When I console.log Array(x+1)
it gives this strange output:
Array(x+1) (3) [empty × 3]
I am aware that there exists a repeat()
method on strings which can be used happily to achieve the same result as the presented function. But as I've come across it, I would like to know the mechanism behind Array(x+1)
. I also know what an array or new Array()
is. But this I see for the first time.