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
The Array join function probably looks something like this (the real implementation will surely be more involved, but this is the basics):
Note in particular the use of
this. In javascript, the meaning ofthisis usually not figured out until you actually call the function. So under normal circumstances, you'll do something like[1, 2, 3].join('-'), and at the time you do that call, javascript will bindthisto be the[1, 2, 3]array, then run the code to produce a string.But it's possible to tell javascript to use something else as
thisand run the function anyway. That's what's happening in the code you're asking about.Array.prototype.join.call(word, "-");says to call the join function, but to forcethisinside the function to equalword. As the function runs, it will do all the same instructions that it would normally do on an array, but instead it does it on thewordstring. If you step through the function in your mind, you'll notice that all the instructions are still sensible ifthisis a string rather than an array:this.lengthis perfectly legal ifthisis a string, and so too isthis[i]for grabbing a character out of a string. So the join function ends up working just fine.