0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Reverse Words in String

Use str.split(' ').reverse().join(' ') to reverse the words in a string in JavaScript, for example: const reversed = str.split(' ').reverse().join(' ');.
📋

Examples

Inputhello world
Outputworld hello
InputJavaScript is fun
Outputfun is JavaScript
Inputsingle
Outputsingle
🧠

How to Think About It

To reverse words in a string, first split the string into individual words using spaces as separators, then reverse the order of these words, and finally join them back together with spaces to form the reversed string.
📐

Algorithm

1
Get the input string.
2
Split the string into an array of words using space as the separator.
3
Reverse the order of the words in the array.
4
Join the reversed words back into a single string with spaces.
5
Return or print the reversed string.
💻

Code

javascript
function reverseWords(str) {
  return str.split(' ').reverse().join(' ');
}

const input = "JavaScript is fun";
const output = reverseWords(input);
console.log(output);
Output
fun is JavaScript
🔍

Dry Run

Let's trace the input "JavaScript is fun" through the code.

1

Split string into words

"JavaScript is fun".split(' ') => ["JavaScript", "is", "fun"]

2

Reverse the array

["JavaScript", "is", "fun"].reverse() => ["fun", "is", "JavaScript"]

3

Join reversed words

["fun", "is", "JavaScript"].join(' ') => "fun is JavaScript"

StepWords Array
After split["JavaScript", "is", "fun"]
After reverse["fun", "is", "JavaScript"]
After join"fun is JavaScript"
💡

Why This Works

Step 1: Splitting the string

Using split(' ') breaks the string into an array of words separated by spaces.

Step 2: Reversing the array

The reverse() method reverses the order of elements in the array, changing the word order.

Step 3: Joining words back

Finally, join(' ') combines the reversed words into a single string with spaces.

🔄

Alternative Approaches

Using a for loop to build reversed string
javascript
function reverseWordsLoop(str) {
  const words = str.split(' ');
  let reversed = '';
  for (let i = words.length - 1; i >= 0; i--) {
    reversed += words[i] + (i === 0 ? '' : ' ');
  }
  return reversed;
}

console.log(reverseWordsLoop('hello world'));
This method manually reverses words using a loop, which is more verbose but shows the process clearly.
Using recursion to reverse words
javascript
function reverseWordsRec(str) {
  const words = str.split(' ');
  if (words.length <= 1) return str;
  return reverseWordsRec(words.slice(1).join(' ')) + ' ' + words[0];
}

console.log(reverseWordsRec('hello world'));
Recursion reverses words by calling itself on the smaller array, but is less efficient for long strings.

Complexity: O(n) time, O(n) space

Time Complexity

Splitting, reversing, and joining each take linear time proportional to the number of words, so overall time is O(n).

Space Complexity

Extra space is used to store the array of words, so space complexity is O(n).

Which Approach is Fastest?

The built-in split-reverse-join method is fastest and most readable; loops and recursion are slower and more complex.

ApproachTimeSpaceBest For
split-reverse-joinO(n)O(n)Simple and fast for most cases
for loop reversalO(n)O(n)Clear manual control, educational
recursionO(n^2)O(n)Demonstrating recursion, less efficient
💡
Use split, reverse, and join together for a simple and fast solution.
⚠️
Forgetting to join the reversed array back into a string, which results in an array output instead of a string.