Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Array.prototype.join.call do in the background for a string?

Tags:

javascript

var a = "foo";
var c = Array.prototype.join.call( a, "-" ); // 'f-o-o'

How does the second line of code work? I don't see any conversion of the string to an array and then converting back again, is this happening in the background? I've encountered this kind of code and it's very weird, an array method accepting a string.

like image 814
daremkd Avatar asked Feb 20 '26 10:02

daremkd


2 Answers

See the specification for Array.prototype.join (below). It doesn't require that the this it's operating on be an array, merely that it have a length and properties with names like 0, 1, and so on. Strings do, and so join can work on a string.

From the spec:

NOTE 2 The join function is intentionally generic; it does not require that its this value be an Array object. Therefore, it can be transferred to other kinds of objects for use as a method.

Here's the full algorithm from the spec:

  1. Let O be ToObject(this value).
  2. ReturnIfAbrupt(O).
  3. Let len be ToLength(Get(O, "length")).
  4. ReturnIfAbrupt(len).
  5. If separator is undefined, let separator be the single-element String ",".
  6. Let sep be ToString(separator).
  7. ReturnIfAbrupt(sep).
  8. If len is zero, return the empty String.
  9. Let element0 be Get(O, "0").
  10. If element0 is undefined or null, let R be the empty String; otherwise, let R be ToString(element0).
  11. ReturnIfAbrupt(R).
  12. Let k be 1.
  13. Repeat, while k < len
    1. Let S be the String value produced by concatenating R and sep.
    2. Let element be Get(O, ToString(k)).
    3. If element is undefined or null, let next be the empty String; otherwise, let next be ToString(element).
    4. ReturnIfAbrupt(next).
    5. Let R be a String value produced by concatenating S and next.
    6. Increase k by 1.
  14. Return R.
like image 50
T.J. Crowder Avatar answered Feb 23 '26 01:02

T.J. Crowder


A string is an Array like object, because it has the property length and you can access its elements (chars) using [] as of that you can apply most of the array manipulation operations on it.

The Function.prototype.call() calls the function given function with using the first parameter as this and the flowing one as normal parameters.

As of that Array.prototype.join.call(a, "-") will call the function join on the object a in you case the string.

like image 44
t.niese Avatar answered Feb 22 '26 23:02

t.niese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!