Join Array with join()
Write a JavaScript function that takes an array of strings and a separator, and returns a single string where each element is joined by the separator using Array.join().
Array.prototype.join() is a JavaScript method that creates and returns a new string by concatenating all elements in an array, separated by a specified separator string. If the separator is omitted, elements are separated with a comma. If an element is undefined or null, it is converted to an empty string.
The join() method is the inverse of split(). Together they form a powerful pattern for string manipulation: split a string into an array, manipulate the array, then join it back. This pattern is idiomatic JavaScript and is widely used for formatting output, CSV generation, and URL construction.
Time complexity is O(n) where n is the total length of the resulting string. Space complexity is O(n) for the result string. The method does not modify the original array.
Edge cases include empty array (returns empty string), single-element array (returns the element without separator), undefined/null elements (converted to empty string), and using an empty string as separator (concatenates without any gap).
Example Input & Output
Join with hyphen
Join with space
Join with empty string
Single element, no separator added
Empty array returns empty string
Algorithm Flow
Solution Approach
Combine all elements of an array into a single string using join(). The method takes a separator string and concatenates all array elements with that separator between them. If no separator is provided, commas are used by default. The original array remains unchanged since join() returns a new string.
join() is the opposite of split(). For arrays containing non-string elements like numbers or booleans, each element is automatically converted to a string before joining. This method is commonly used for constructing CSV data, URL parameters, and readable lists.
Time complexity is O(n), space complexity is O(n).
Best Answers
function solution(arr, sep) {
return arr.join(sep);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
