Array methods on string objects

Take this code:

var word = "foo";

var hyphenWord = Array.prototype.join.call(word, "-"); // returns "f-o-o-b-a-r"

Please explain step by step what is happening with hyphenWord. How can a hyphen be concatenated to a string using call()?

3 comments · 60% upvoted · other discussions

comments

inu-no-policemen

You can also do this kind of thing with an array literal + spread:

> [...'foo']
(3) ["f", "o", "o"]

Now that you've turned that array-like into an actual array, the array methods are available.

> [...'foo'].join('-')
"f-o-o"