Avatar ·

How to work with strings in JavaScript?

Hello everyone! I'm working with Node.js and encountered a problem with string processing. I need to implement a function that takes an array of strings and returns a formatted output: join the strings with a comma, but the last element should be separated by the conjunction "and". For example: ['apple', 'banana', 'orange'] → 'apple, banana and orange'.

I tried using Array.prototype.join(', '), but it adds a comma before the last element, whereas I need to replace it with " and". I attempted to write it manually using a for loop with index checking, but the code ends up cumbersome and doesn't handle edge cases (empty array, single element).

Here's my current code:

function formatList(arr) {\n  if (arr.length === 0) return '';\n  if (arr.length === 1) retu