String Reversal with JavaScript

matt readout
4 min readAug 4, 2019

--

A brief look at a couple solutions to a common technical interview question

Two people with laptops conducting an interview
Photo by Charles 🇵🇭 on Unsplash

Not only is the problem of reversing a string a very common question to be asked in a technical interview, it can so often be a step required in approaching so many other problems! Say we’re given the directions:

Write a function that, when given a string, will return a new string with the same characters in reversed order

For example, we should expect reverse('string') to return 'gnirts', and reverse('Hello World!') to return '!dlroW olleH'.

How should we approach this? From our knowledge of strings in JavaScript, we know that we unfortunately don’t have any kind of reverse() method included with the String prototype (that’d be too easy!). However, we do have access to a very similar helper method for arrays! Sure enough, calling the reverse() method on an array reverses it in place. Using this as our starting point, we can now make use of a string helper method to take our string input, convert it to an array of characters, on which we can call reverse() to reverse the order of the array, and then convert the reversed array back into a string that our function can return.

Let’s first convert our string into an array, calling the split() method on it:

function reverse(str) {
str.split('')
}

split() takes an argument of a string that will determine where the splits will happen. By passing in an empty string '' our input string will be split on each individual character. So, if we’re calling reverse('apple'), the result of str.split('') will be the array ['a', 'p', 'p', 'l', 'e']. This is good — we can work with this! Now that we have an array, we can call reverse():

function reverse(str) {
let reversedArray = str.split('') //assign it to a temp variable
reversedArray.reverse()
}

At this point, using the above example, reversedArray should point to the array ['e', 'l', 'p', 'p', 'a']. We’re getting close. Now we just need to take this array and convert it back to a string. Luckily for us, we can use the join() method to perform the opposite of the split() from before. Called on an array, join() creates and returns a string by concatenating all of the elements of an array. It takes an optional argument of a separator character. In our case, we can call it with another empty string:

function reverse(str) {
let reversedArray = str.split('')
reversedArray.reverse()
reversedArray.join('')
}

Using our reverse('apple') example, we expect this to create the string 'elppa', exactly what we’re looking for! Now let’s put everything together, and make our code a little less repetitive:

function reverse(str) {
return str.split('').reverse().join('')
}

There’s not really any need to store the array we created in a temporary variable, so we can chain the method calls and return the result. Done! However, what if we’re specifically forbidden (forbade?) from using the reverse() array method? After all, it did make things very simple. A little too simple, perhaps..

Another Solution

Let’s think about how we might do this manually, as if we had a line of letters on the table in front of us that we could move around with our hands. If we started from the first letter in the line, we could one-by-one go through and move each letter to the front, resulting in a reversed version of the original string. For example:

'apple' // starting point, move 'a' to front
'paple' // move second character 'p' to front
'ppale' // move next 'p' to front
'lppae' // move 'l' to front
'elppa' // move 'e' to front, resulting in reversed 'apple'

How could we write the code to do this? To iterate through the whole string, one option would be to use a for loop. Now, we could write the standard for(var i = 0; i < str.length; i++) syntax. However, we’re modern JavaScript engineers, so let’s use a feature of ES6 — the for...of statement:

function reverse(str) {
let reversedString = ''
for (char of str) {
reversedString = char + reversedString
}
return reversedString
}

In this solution, we declare a temporary variable reversedString and initialize it with an empty string. This is the string we’ll be building by adding each character in sequence to the beginning of the line. Calling for (char of str) will iterate through the string that was passed in, performing an action on each iteration. In our case, we’ll be taking each character and adding it to the beginning of reversedString. For our ‘apple’ example, on the first pass through str, we’ll take char at that point (first up is ‘a’) and add it to reversedString, making it 'a'. On the next pass (the letter ‘p’ is up next), reversedString will be 'pa', and so on until we have fully reversed the input string.

This solution is great because not only does it show your interviewer that you understand the actually process of reversing a string (without relying on helper methods), but also that you’re up to date on the latest features of JavaScript!

--

--