How to reverse a string in JavaScript?

Common and rather simple question during a job interview can be: How to reverse a string. In this article we are going to use JavaScript as our language. However, the solutions discussed here should be really easy to apply in other programming languages too.
Let’s define the problem and expected outcome first. We start with a string:
const string = ‘abcdef’;
Our expected outcome is:
const expected = 'fedcba';
First solution is based on classic for loop. Basically, we start at the end of the string and loop over all characters in reverse order:
function reverse(string) {
let reversed = '';
for (let i = string.length - 1; i >= 0; i -= 1) {
reversed += string[i];
}
return reversed;
}
We can rewrite the same code with the newer for…of syntax:
function reverse(string) {
let reversed = '';
for (const character of string) {
reversed = character + reversed;
}
return reversed;
}
Let’s note that in this case we are not looping in reverse order. Instead we are appending characters in reverse order (append characters to beginning of reversed variable).
Second solution is based on Array.prototype.reverse() method.
All strings are in fact arrays of characters. We took advantage of this in previous solution by addressing individual characters in a string by using its index.
However, we can’t simply run:
string.reverse(); // this won’t work
Strings in JavaScript are immutable. Therefore, in order to do this, we need to convert string to an array of single strings first. Arrays are mutable and we will be able to change it:
function reverse(string) {
const array = string.split('');
array.reverse();
return array.join('');
}
The first line of our solution is splitting the string into an array. Next, we reverse order and finally, we join the array back as a single string and return the result.
Additionally, we can combine all three lines of code into a single one:
function reverse(string) {
return string.split('').reverse().join('');
}
The last solution is based on Array.prototype.reduce() method and functional programming.
Reduce works on each element of an array, applies given function and returns a single value.
Let’s start by converting string into an array of strings by using split(‘’)
method. Then we can use reduce(callback, initialValue)
.
First parameter: callback
is an arrow function that takes two parameters: accumulator
— is the reversed string and currentValue
— is current character in the array. The second parameter, initialValue
is an empty string ‘’
that we want to use to store reversed value (it’s basically equivalent if let reversed = ‘’;
in the other solutions)
function reverse(string) {
return string.split('').reduce((reversed, character) => {
return character + reversed;
}, '');
}
In this article we covered three different ways of reversing string. From a very classical one, through Array helper and finished with reduction and functional programming.
If you like what you have read, please follow me.