2

i can't understand how Array.join works if separator is an array in Javascript ? I find a detail explanation how it works. My example below

arr1 = ['a','b','c'];
arr2 = ['d', 'e', 'f'];
arr1.join(arr2);

//Output
"ad,e,fbd,e,fc"
2
  • Hint 1: what string joins all the elements (from arr1)? Hint 2: what happens when an array is coerced into a string (eg. "" + arr2)? Commented Dec 20, 2018 at 6:29
  • 5
    First arr2 will be converted to a string using Array.prototype.toString() and return value (string) will be used to join elements in arr1. Commented Dec 20, 2018 at 6:29

2 Answers 2

2

The join method accepts a separator and you're passing an array as separator. So, the join method will first transform it to a string: 'd,e,f'

Thus,

ad,e,f
bd,e,f
c // last remains same - no join 
// as you may do like ['a','b','c'].join('-') results a-b-c

And final result:

ad,e,fbd,e,fc

You may read this note on docs:

Separator

Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If separator is an empty string, all elements are joined without any characters in between them.

Sign up to request clarification or add additional context in comments.

Comments

1

JavaScript is a flexible language. If it will receive something other than it is expecting, it will try to convert the passed value into a form / type that it is expecting.

As from Docs, Array's .join() method expects a string in argument to be used as a separator for joining array elements. In case you will pass it an array, JavaScript will convert this array into a string internally by calling .toString() method of Arrays. And this returned string i.e d,e,f will be used as a separator to join elements in outer array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.