Reversing the even length words of a string in JavaScript

We are required to write a JavaScript function that takes in a string and reverses the words in the string that have an even number of characters in them.

Let's say the following is our string:

const str = 'This is an example string';

We want to reverse the even length words of the above string i.e. reverse the following words:

This (4 characters)
is (2 characters)  
an (2 characters)
string (6 characters)

The word "example" has 7 characters (odd length), so it remains unchanged.

Syntax

function reverseEvenWords(str) {
    return str.split(' ')
              .map(word => word.length % 2 === 0 ? word.split('').reverse().join('') : word)
              .join(' ');
}

Method 1: Using Array.reduce()

const str = 'This is an example string';

const isEven = str => !(str.length % 2);

const reverseEvenWords = (str = '') => {
    const strArr = str.split(' ');
    return strArr.reduce((acc, val) => {
        if(isEven(val)){
            acc.push(val.split('').reverse().join(''));
            return acc;
        };
        acc.push(val);
        return acc;
    }, []).join(' ');
};

console.log(reverseEvenWords(str));
sihT si na example gnirts

Method 2: Using Array.map()

const str = 'This is an example string';

const reverseEvenWords = (str = '') => {
    return str.split(' ')
              .map(word => {
                  return word.length % 2 === 0 
                      ? word.split('').reverse().join('') 
                      : word;
              })
              .join(' ');
};

console.log(reverseEvenWords(str));
sihT si na example gnirts

How It Works

The solution follows these steps:

  1. Split the string into an array of words using split(' ')
  2. Check each word's length using the modulo operator %
  3. Reverse even-length words by splitting into characters, reversing, and joining back
  4. Keep odd-length words unchanged
  5. Join the array back into a string with spaces

Comparison

Method Readability Performance
Array.reduce() More verbose Good
Array.map() Cleaner, more functional Good

Conclusion

Both methods effectively reverse even-length words in a string. The map() approach is more concise and functional, while reduce() offers more explicit control over the accumulation process.

Updated on: 2026-03-15T23:19:00+05:30

403 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements