# Rewrite of Array.join

While rewriting Array so I can practice my javascript, I looked at my implementation of .join(). It seems a little clunky to me.

I've tried to cover all the edges, like making sure separator isn't null before joining, not adding the separator at the end of the string, and writing some documentation.

What I'm looking for is a smoother way to write this function. Any recommendations about this function are appreciated and considered.

/**
* Converts each element of the array to string then concats them.
*
* @param separator Value to separate the elements by.
*
* @return String of joined elements.
*/
ArrayRewrite.prototype.join = function(separator) {
separator = separator || "";
let string = "";
for (let i = 0; i < this.content.length; i++) {
string += (i !== this.content.length - 1)
? this.content[i] + separator
: this.content[i]
;
}
return string;
}


A test case is below

// This is the main function that other functions are built onto //
function ArrayRewrite(...elements) {
this.content = elements || [];
}

myArray = new ArrayRewrite("Hello", "Testing", "Testing Again");
console.log(myArray.join(", "))

// Output:
// Hello, Testing, Testing Again

• separator = separator || ""; What's the purpose of this? (Please forgive me if this is a basic question) – Srivaths Feb 10 at 17:57
• @Srivaths If separator is not passed into the function, that line sets it to "". The line says "separator = (separator if passed) (or if not passed) (set separator to ""); – Linny Feb 10 at 18:57
• Ohh, I believe that's only possible in JavaScript! Thanks a lot! – Srivaths Feb 10 at 19:04

A short review;

• You probably want to cache this.content.length
• That check for the end of array is clunky
• separator will change from 0 to "", an unlikely edge case, but it could happen
• Why are array elements in this.content ? I would have gone for this[i] instead
• string is not very evocative, I went with out

Obligatory rewrite;

Array.prototype.myJoin = function stringMyJoin(separator) {
separator = separator || "";
let out = this[0];
const length = this.length;
for (let i = 1; i < length; i++) {
out += separator + this[i];
}
return out || "";
}

console.log([].myJoin(","), [].myJoin(",") === "");
console.log(["apple"].myJoin(","));
console.log(["apple","bear","bananers"].myJoin(","));

• "separator will change from 0 to """ - when will this happen? e.g. if the parameter is undefined, per first line of the function? – Sᴀᴍ Onᴇᴌᴀ Feb 11 at 17:15
• console.log(["a","b"].myJoin(0)) will return ab – konijn Feb 12 at 12:00