Reverse Words with Method Chaining
Write a JavaScript function that reverses the order of words in a sentence using method chaining with split(), reverse(), and join(). Method chaining is a JavaScript programming pattern where multiple methods are called sequentially on the result of the previous method, creating a concise and readable pipeline.
Start by splitting the input string into an array of words using split() with a space delimiter. Each word becomes an element in the array. Then call reverse() on the array to reverse the element order in-place. Finally, call join() with a space delimiter to combine the reversed words back into a single string.
This split-reverse-join pattern is one of the most common method-chaining idioms in JavaScript. Each method transforms the data in a specific way: split converts string to array, reverse changes array order, join converts array back to string. The chaining syntax avoids intermediate variables and expresses the data flow as a single pipeline.
Time complexity is O(n) where n is the string length. Split, reverse, and join each iterate through the elements once. Space complexity is O(n) for the intermediate array. The method chain is efficient and idiomatic, used commonly in JavaScript string manipulation tasks.
Edge cases include single-word strings (reverse does nothing, join returns the word), empty strings (split returns array with empty string, reverse and join return empty string), and strings with multiple spaces between words.
Example Input & Output
Reverse two words
Reverse four words
Single word
Reverse three words
Single word stays same
Algorithm Flow

Solution Approach
Reverse the characters in a string by chaining split(), reverse(), and join(). Split the string into an array of characters, reverse the array, then join the characters back into a string.
This method string is a common JavaScript idiom for string reversal. Each method transforms the data: string to array, array reversed, array back to string.
Time O(n), Space O(n).
Best Answers
function solution(sentence) {
return sentence.split(' ').reverse().join(' ');
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
