Reverse all the words of sentence JavaScript

We are required to write a JavaScript function that takes in a string and returns a new string which has all the words reversed from the original string.

For example −

If the original string is −

"Hello World how is it outside"

Then the output should be −

"olleH dlroW woh si ti edistuo"

Now, let's write the code for this function −

Example

const str = 'Hello World how is it outside';
const reverseSentence = str => {
    const arr = str.split(" ");
    const reversed = arr.map(el => {
        return el.split('').reverse().join("");
    });
    return reversed.join(" ");
};
console.log(reverseSentence(str));

Output

The output in the console will be −

olleH dlroW woh si ti edistuo

How It Works

The function works in four steps:

  1. split(" ") − Splits the sentence into an array of individual words
  2. map() − Iterates through each word in the array
  3. split('').reverse().join("") − For each word, splits it into characters, reverses the order, and joins them back
  4. join(" ") − Combines all reversed words back into a single sentence with spaces

Alternative Approach Using For Loop

const str = 'Hello World how is it outside';

function reverseWords(sentence) {
    const words = sentence.split(" ");
    const result = [];
    
    for (let i = 0; i 

olleH dlroW woh si ti edistuo

Conclusion

Both methods effectively reverse individual words in a sentence while maintaining word order. The map() approach is more concise, while the for loop provides clearer step-by-step logic for beginners.

Updated on: 2026-03-15T23:18:59+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements