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
Depending on the implementation of a method - any method - what it can operate on may or may not be very strict. It can be the object for which the method was originally designed, or some other method entirely. Because JavaScript isn't typed, there's no inherent type checking involved in these operations and usually its just assumptions that are made or simple duck typing checks that are used.
Most, if not all, of the Array methods work on Array-like objects. This means any object with indexed values (values with numeric keys accessible via
[0],[1], etc.) and alengthproperty. Run an Array method on an object that has this behavior (usingcall), and it will be treated like an array. Things that are array-like but not arrays in JavaScript include theargumentsobject in functions, and strings.The creation of
hyphenWordworks becausewordcan be treated like an array. It has indexed properties which point to each character in the string"foo"("foo"[0] === "f") and alengthproperty indicating how many characters are there. So whenjoinis called onword,joinsees it no different as["f", "o", "o"]. The result of the operation is the same.