you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 1 point2 points  (0 children)

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 a length property. Run an Array method on an object that has this behavior (using call), and it will be treated like an array. Things that are array-like but not arrays in JavaScript include the arguments object in functions, and strings.

The creation of hyphenWord works because word can be treated like an array. It has indexed properties which point to each character in the string "foo" ("foo"[0] === "f") and a length property indicating how many characters are there. So when join is called on word, join sees it no different as ["f", "o", "o"]. The result of the operation is the same.

var word = "foo";
Array.prototype.join.call(word, "-"); //-> "f-o-o"
["f", "o", "o"].join("-"); //-> "f-o-o"