What Is String Reversal?
String reversal is the process of creating a new string whose characters appear in the
opposite order from the original string. For example, reversing
"hello" produces
"olleh".
Input: "hello"
Output: "olleh"
String reversal is a simple problem, but it introduces several important programming concepts, including character traversal, arrays, indexes, stacks, and the difference between creating a new value and modifying existing data.
Why String Reversal Is Useful
Reversing a string is commonly used as a beginner exercise and also appears as part of larger algorithms. It can help developers understand how to process characters from either direction and how data structures such as stacks naturally produce reversed order.
- Learning string traversal
- Understanding indexes and character positions
- Practicing array and stack operations
- Solving palindrome-related problems
- Processing text in reverse order
- Preparing for coding interview questions
Reversing a String with a Loop
One of the clearest approaches is to traverse the string from its last character to its first character and build the result one character at a time.
function reverseString(text) {
let result = "";
for (let i = text.length - 1; i >= 0; i--) {
result += text[i];
}
return result;
}
console.log(reverseString("hello"));
// olleh
If the input is "hello", the loop starts at index
4 and processes the characters in this order:
o,
l,
l,
e,
h.
Understanding the Indexes
JavaScript strings use zero-based indexing. For the word
"CODE", the indexes are:
Character: C O D E
Index: 0 1 2 3
To reverse the string, we start at
length - 1, which is index 3, and move toward
index 0.
E → D → O → C
Result: "EDOC"
Using an Array and reverse()
JavaScript provides a convenient way to reverse the characters by converting the string into an array, reversing the array, and joining it back into a string.
function reverseString(text) {
return text.split("").reverse().join("");
}
console.log(reverseString("developer"));
// repoleved
The three operations perform different jobs:
split("")converts the string into an array of characters.reverse()reverses the array.join("")combines the characters into a string again.
Reversing with a Stack
A stack naturally supports string reversal because it follows the Last In, First Out (LIFO) principle. If every character is pushed onto a stack, popping the characters returns them in reverse order.
function reverseWithStack(text) {
const stack = [];
for (const char of text) {
stack.push(char);
}
let result = "";
while (stack.length > 0) {
result += stack.pop();
}
return result;
}
console.log(reverseWithStack("hello"));
// olleh
For "hello", the stack first contains
h, e, l, l, o. Popping repeatedly produces
o, l, l, e, h.
Two-Pointer Reversal
Another common technique is the two-pointer approach. The first pointer starts at the beginning of the character array and the second starts at the end. The characters are swapped while the pointers move toward the center.
function reverseString(text) {
const chars = text.split("");
let left = 0;
let right = chars.length - 1;
while (left < right) {
[chars[left], chars[right]] = [chars[right], chars[left]];
left++;
right--;
}
return chars.join("");
}
console.log(reverseString("hello"));
// olleh
The two-pointer method is especially useful when working with mutable character arrays because it demonstrates how a sequence can be reversed through swaps rather than repeatedly constructing the result from one end.
Step-by-Step Two-Pointer Example
Consider the string "CODE". After converting it
into an array, the two pointers begin at opposite ends.
[C, O, D, E]
↑ ↑
left right
Swap C and E:
[E, O, D, C]
↑ ↑
left right
Then swap O and D:
[E, D, O, C]
Result: "EDOC"
Recursive String Reversal
String reversal can also be expressed recursively. The idea is to move the first character to the end of the reversed remainder of the string.
function reverseString(text) {
if (text.length <= 1) {
return text;
}
return reverseString(text.slice(1)) + text[0];
}
console.log(reverseString("hello"));
// olleh
The base case handles an empty string or a single-character string. The recursive calls continue until the input reaches that base case, after which the characters are assembled in reverse order.
Although this approach is useful for understanding recursion, it is generally not the first choice for large strings because recursive calls consume call-stack space.
Handling Spaces
A basic reversal treats spaces as ordinary characters. Therefore, the spaces remain in the string but move to their corresponding reversed positions.
const text = "hello world";
console.log(text.split("").reverse().join(""));
// dlrow olleh
This is different from problems that ask you to reverse the order of words while
keeping each word unchanged. For example, reversing the words in
"hello world" produces
"world hello".
Reversing Words Instead of Characters
When the requirement is to reverse word order, split the sentence into words rather than individual characters.
function reverseWords(sentence) {
return sentence
.split(" ")
.reverse()
.join(" ");
}
console.log(reverseWords("learn data structures"));
// structures data learn
Carefully identifying whether the problem asks for character reversal or word reversal is important. The two operations produce different results.
String Reversal and Palindromes
Reversal is closely related to palindrome problems. A palindrome reads the same forward and backward. One simple way to check this is to compare a string with its reversed version.
function isPalindrome(text) {
const reversed = text.split("").reverse().join("");
return text === reversed;
}
console.log(isPalindrome("level"));
// true
console.log(isPalindrome("hello"));
// false
For performance-sensitive palindrome problems, a two-pointer comparison can avoid constructing a complete reversed string.
Comparing Reversal Approaches
| Approach | Time | Extra Space | Main Idea |
|---|---|---|---|
| Backward loop | O(n) | O(n) | Read characters from right to left |
| split + reverse + join | O(n) | O(n) | Reverse a character array |
| Stack | O(n) | O(n) | Use LIFO ordering |
| Two pointers | O(n) | O(n) for a JS character array | Swap characters from both ends |
| Recursion | O(n) typical | O(n) call stack and intermediate values | Reverse the remaining substring recursively |
An Important JavaScript Detail
JavaScript strings are immutable. This means an existing string cannot be changed
character by character in place. Techniques such as
split() create an array that can be modified,
after which join() creates the resulting string.
This distinction is useful when comparing string algorithms across programming languages. A technique that modifies a character array in place may have different implementation details in a language with mutable character arrays.
Unicode and User-Visible Characters
For ordinary English text, iterating over a JavaScript string character by character is usually straightforward. However, some Unicode symbols are represented using multiple UTF-16 code units. For applications that need to reverse user-visible characters accurately, Unicode grapheme handling requires additional care.
For typical data-structure exercises using basic ASCII characters, the standard approaches shown above are sufficient. Production text-processing code should define its Unicode requirements before choosing an implementation.
Common Mistakes
-
Starting the loop at
text.lengthinstead oftext.length - 1. - Accidentally skipping the first character by stopping the loop too early.
- Confusing character reversal with reversing the order of words.
- Forgetting that JavaScript strings are immutable.
- Using recursion unnecessarily when a simple iterative solution is sufficient.
- Assuming basic character iteration always handles every Unicode grapheme as one visible character.
Choosing an Approach
For everyday JavaScript code, split("").reverse().join("")
is concise and easy to understand. For learning algorithms, a backward loop or
two-pointer implementation demonstrates the underlying logic more clearly.
If the purpose of the exercise is to demonstrate a stack, use the stack approach. In an interview, explain why the selected approach fits the problem instead of relying only on a built-in method.
Key Takeaways
- String reversal places characters in the opposite order.
- A backward loop can reverse a string in linear time.
- An array can be reversed using split(), reverse(), and join().
- A stack naturally reverses data because it follows LIFO order.
- Two pointers can reverse a mutable character array through swaps.
- JavaScript strings are immutable, so reversal creates a resulting string rather than modifying the original.
- Always distinguish character reversal from word-order reversal.