Strings · beginner
JavaScript Program to Reverse a String
Reverse a string in JavaScript with split, reverse and join, with a for loop, and with Array.from() for emoji, then reverse the order of words in a sentence.
- split()
- Array.prototype.reverse()
- join()
- Array.from()
Strings in JavaScript cannot be changed in place and have no reverse() method. Reversing means building a new string, most often by converting to an array, reversing the array and joining it back.
Reversing the letters and reversing the words are two different tasks, and the program shows both.
The program
const text = "Hello, World";
console.log(text.split("").reverse().join(""));
let result = "";
for (const ch of text) {
result = ch + result;
}
console.log(result);
const sentence = "JavaScript is fun";
console.log(sentence.split(" ").reverse().join(" "));dlroW ,olleH
dlroW ,olleH
fun is JavaScriptHow it works
- split("") turns the string into an array of characters.
- reverse() reverses that array in place, and join("") glues it back into a string.
- The for...of loop puts each character in front of the result so far, so the first character ends up last.
- To reverse the order of words, split on spaces instead of on every character.
Watch it run line by line
Step through the for...of loop and watch result grow from the left: "H", "eH", "leH", … until the whole string is reversed.
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Safe for emoji: Array.from()
split("") splits a string into UTF-16 code units, which breaks emoji into two halves. Array.from() and the spread operator split by code points, so emoji survive.
const text = "ab😀";
console.log(text.split("").reverse().join("") === "😀ba");
console.log(Array.from(text).reverse().join(""));false
😀baCommon mistakes
- Calling reverse() on the string itself, which throws "text.reverse is not a function".
- Forgetting that reverse() changes the array in place: if you keep the array, the original order is gone.
- Using split("") on text with emoji, which produces broken characters.
Try it yourself
- Reverse each word but keep the word order: "JavaScript is fun" → "tpircSavaJ si nuf".
- Write a recursive reverse(s) = reverse(s.slice(1)) + s[0].
- Check whether a sentence reads the same backwards word by word ("fall leaves after leaves fall").
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.