How to reverse a string in JavaScript?

Image for post
Image for post

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:

Our expected outcome is:

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:

We can rewrite the same code with the newer for…of syntax:

Lets 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:

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:

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:

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)

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.

Written by

Programming, project management and politics

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store