Lessons · TypeScript · join (pieces to text)
Gluing a list into text
arr.join(sep) makes one string with sep between the items. split does the reverse.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
A comma-separated line for a file, a path from segments, tags shown with a dot between them: join is how a list becomes something a person reads.
How to think about it
Choose the separator to match the format: ',' for CSV-like output, '' to run items together, '\n' for lines. Convert items to the text you want first; join calls String on each.
Worked example
console.log([1, 2, 3].join("-"));1-2-3.console.log(["a", "b"].join(""));ab: an empty separator runs them together.console.log([1, 2].join());1,2: the default separator is a comma.
console.log("1-2-3".split("-"));[ '1', '2', '3' ]: split is the inverse.Your turn
One CSV line from the fields.
const line = fields.(",");Solve one with the tests running
The trap
join turns null and undefined into empty strings: [null, undefined].join('-') is '-'. Filter them out first if they should not vanish.
Practise join (pieces to text) on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.