Reverse the words in a sentence in JavaScript
Beginner · 4 min read
"Reverse this sentence" sounds like one clear task, but it can mean three different things. Reverse the order of the words? Reverse the letters inside each word? Or flip every single character? Interviewers ask this question often, and the usual way to fail is to answer a different version from the one they asked.
In this tutorial you will take Ikeja to Yaba by bus and produce all three, using split, reverse and join. Along the way you'll learn why reverse can change data you didn't mean to touch, and why emoji need special care. You should know what strings, arrays and map are.
The three tools
split(' ')cuts a string at every space and gives you an array of words.reverse()flips the order of the items in an array.join(' ')glues an array back into a string, with a space between items.
const words = 'Ikeja to Yaba'.split(' ');
console.log(words); // [ 'Ikeja', 'to', 'Yaba' ]
console.log(words.reverse().join(' ')); // Yaba to Ikeja
reverse changes the array itself
Most array methods you've met, like map, return a new array and leave the original alone. reverse doesn't. It rearranges the array you call it on, and also returns that same array. Changing the original like this is called mutating it. Keep that in mind; it comes back in Step 4.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
111 Reverse the words, not the letters
easyGiven Ikeja to Yaba by bus, produce the words in the opposite order, then the letters of each word reversed in place, then the whole line reversed character by character. Three different jobs, three different answers.
Stuck? Three hints, smallest first
- 1. Reversing word order is
split,reverse,join. - 2.
reverse()changes the array it is called on, so copy first if the original still matters. - 3.
[...text]walks whole characters wheresplit('')walks UTF-16 units.
Step 1: reverse the word order
const line = 'Ikeja to Yaba by bus';
const wordsReversed = line.split(' ').reverse().join(' ');
console.log(wordsReversed); // bus by Yaba to Ikeja
Split into words, flip the array, join with spaces. Each method hands its result to the next, so the three calls chain on one line.
Step 2: reverse the letters inside each word
Now the words stay in place but each one is spelled backwards:
const line = 'Ikeja to Yaba by bus';
const eachWordReversed = line.split(' ').map((w) => [...w].reverse().join('')).join(' ');
console.log(eachWordReversed); // ajekI ot abaY yb sub
map visits each word. Inside it, [...w] spreads the word into an array of letters, reverse() flips them, and join('') glues them back with nothing between. The outer join(' ') puts the spaces back.
Step 3: reverse every character
const line = 'Ikeja to Yaba by bus';
const lettersReversed = [...line].reverse().join('');
console.log(lettersReversed); // sub yb abaY ot ajekI
This treats the whole line as one long list of characters, spaces included. Compare it with Step 2: the letters inside each word are the same, but the words are in the opposite order. Three jobs, three answers.
Step 4: don't mutate what isn't yours
In Step 1, split had just made a brand-new array, so reversing it hurt nobody. It's different when the array already exists:
const words = 'Ikeja to Yaba by bus'.split(' ');
const copy = [...words].reverse();
console.log(copy[0]); // bus
console.log(words[0]); // Ikeja
words.reverse();
console.log(words[0]); // bus
[...words] makes a copy, so reversing the copy leaves words alone. Calling words.reverse() directly changes words for every other part of the program that uses it. One spread is all it takes to avoid that.
Step 5: why [...text] and not split('')
Inside JavaScript, many emoji are stored as two small pieces called code units. split('') cuts between code units, so it can cut an emoji in half. Spreading with [...text] walks through real characters and keeps each emoji whole:
const bus = 'a\u{1F68C}';
console.log([...bus].reverse().join('') === '\u{1F68C}a'); // true
console.log(bus.split('').reverse().join('') === '\u{1F68C}a'); // false
'\u{1F68C}' is the bus emoji written as a code. The spread version reverses it correctly. The split('') version swaps the two halves of the emoji, and what comes out can't be displayed as a bus.
Step 6: a double space
One more detail. Splitting on a single space keeps gaps exactly as they were:
console.log('Yaba Ojota'.split(' ').reverse().join(' ')); // Ojota Yaba
The double space makes an empty word between the two names, and it is still there after the reverse. That is usually what you want when reversing word order.
The full solution
The answer panel produces all three reversals of the same line, reverses a copy of the word list and then the original, and checks the double space and the bus emoji. Press Run to see the output.
const line = 'Ikeja to Yaba by bus';
const wordsReversed = line.split(' ').reverse().join(' ');
const eachWordReversed = line.split(' ').map((w) => [...w].reverse().join('')).join(' ');
const lettersReversed = [...line].reverse().join('');
// reverse() is in place. Copy with a spread when you need the original after.
const words = line.split(' ');
const copy = [...words].reverse();
const bus = 'a🚌';
console.log(wordsReversed);
console.log(eachWordReversed);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the words come back in the opposite order', wordsReversed, 'bus by Yaba to Ikeja');
test('each word reversed in place is a different thing', eachWordReversed, 'ajekI ot abaY yb sub');
test('and reversing every character is a third thing', lettersReversed, 'sub yb abaY ot ajekI');
test('reversing a copy leaves the original alone', words[0], 'Ikeja');
test('the copy is the reversed one', copy[0], 'bus');
test('reverse on the original does mutate it', words.reverse()[0], 'bus');
test('splitting on a single space preserves a double gap', 'Yaba Ojota'.split(' ').reverse().join(' '), 'Ojota Yaba');
test('spreading keeps an astral character whole', [...bus].reverse().join(''), '🚌a');
test('splitting on an empty string tears it in half', bus.split('').reverse().join('') === '🚌a', false);
"Reverse a string" is three questions wearing one name, and the assertions separate them: word order, letters within each word, and every character in the line. Getting asked for one and delivering another is the usual interview failure.
reverse() mutates. line.split(' ').reverse() is safe because split just made the array, but existingArray.reverse() rearranges the caller's data, which is a bug at a distance — [...existing].reverse() costs one spread and removes the class of problem. The last two assertions are the character-width trap: split('') cuts on UTF-16 units, so a bus emoji becomes two broken halves and reversing them produces a replacement glyph, while [...text] iterates code points and keeps it intact. Also exercise 14, which reversed text to test for a palindrome; here the angle is what "reversed" means when the unit is a word or a character wider than one unit.
Common mistakes
- Answering the wrong question. Ask which reversal is wanted: words, letters in each word, or every character.
- Calling
reverse()on an array you were given. It changes the caller's data. Reverse a copy:[...arr].reverse(). - Using
split('')on text with emoji. It cuts characters in half. Use[...text].
Try it yourself
- Turn
'one, two, three'into'three, two, one'. Which separator should you split and join on? - Write
isWordPalindrome(sentence)that checks whether a sentence reads the same with its words reversed, like'bus to bus'. - Use
toReversed(), a newer array method that returns a reversed copy, and check that the original array is unchanged.