Code Logo

Reverse Words with Method Chaining

Published at25 Jul 2026
JavaScript String Handling Medium 0 views
Like0

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

Example 1
Input
"hello world"
Output
"world hello"
Explanation

Reverse two words

Example 2
Input
"the quick brown fox"
Output
"fox brown quick the"
Explanation

Reverse four words

Example 3
Input
"code"
Output
"code"
Explanation

Single word

Example 4
Input
"one two three"
Output
"three two one"
Explanation

Reverse three words

Example 5
Input
"a"
Output
"a"
Explanation

Single word stays same

Algorithm Flow

Recommendation Algorithm Flow for Reverse Words with Method Chaining
Recommendation Algorithm Flow for Reverse Words with Method Chaining

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.

function solution(s) { return s.split('').reverse().join(''); }

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

javascript - Approach 1
function solution(sentence) {
  return sentence.split(' ').reverse().join(' ');
}