Jalaj Gupta

Jalaj Gupta

Reversing a String in Javascript

Reversing a String in Javascript

Reversing a string is a very common interview question which can be asked to you in phone interview or screening.

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

In this post I will explain different methods to reverse the string using javascript, so without any further ado let get right into it.

Below given code is how I wrote the solution at first, I'll explain it and after that discuss other methods of solving the problem.

function reverseString(str) {
    let arr = str.split("");
    arr.reverse();
    str = arr.join("");
    return str;
}

What above code does is it first uses the split function which splits the passed string object into array of strings by separating strings into substrings.

After that I reversed the array we created above using reverse method. In the last I joined all the elements of array into string using the join method and returned the string.

So that's my solution to the challenge. Now let’s talk about other ways.

To make above code shorter we can chain methods and return immediately.

function reverseString(str){
    return str.split("").reverse().join("");
}

While we're at it we can make it even shorter if we use ES6 arrow function syntax.

const reverseString = str => str.split("").reverse().join("");

Now imagine your interviewer saying, 'Great, now solve it without using these inbuilt methods with a simple for loop.'

Don't sweat yet! Below I'll tell how to do just that...

Reversing a string using for loop

We can also reverse a String without using builtin methods like reverse by using for loop.

function reverseString(str) {
    let newString = "";
    for (i = str.length - 1; i >= 0; i--) {
        newString += str[i];
    }
    return newString;
}

Okay so what I am doing in this code is at first I declared a new variable to hold our reversed string.

After that I created a for loop. The starting point of the for loop is str.length - 1. which is the index of the last character of the string. As long as the value of i is greater than or equal to zero the loop will go on and we decrement the value of i with each iteration.

Checkout the pseudocode explaining the process below.

For example let’s suppose the string passed to the function is “hello”.

Now hello’s length equals 5
For each iteration: i = str.length  1 and newString = newString + str[i]
First iteration: i = 5  1 = 4, newString = “” + “o” = “o”
Second iteration: i = 4  1 = 3, newString = “o” + “l” = “ol”
Third iteration: i = 3  1 = 2, newString = “ol” + “l” = “oll”
Fourth iteration: i = 2  1 = 1, newString = “oll” + “e” = “olle”
Fifth iteration: i = 1  1 = 0, newString = “olle” + “h” = “olleh”
End of the FOR Loop

Aaaand in the last we returned the reversed string.

Hope you got that! If not then don’t hesitate to comment and I’ll be more than happy to help.

Still awake? Let's see yet another method to reverse your strings.

Reversing string using Recursion

In this method, I will use two methods: the String.prototype.substr() method and the String.prototype.charAt() method.

The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.

"hello".substr(1); // "ello"

The charAt() method returns the specified character from a string.

"hello".charAt(0); // "h"

Now the whole code,

function reverseString(str) {
    if (str === "") { // This is the terminal case that will end the recursion
        return "";
    } else {
        return reverseString(str.substr(1)) + str.charAt(0);
    }
}
reverseString("hello"); // olleh

Explanation:

First Part of the recursion method

  We need to remember that there won’t be just one call, we’ll have several nested calls

  Each call will return       reverseString(str.subst(1))   +    str.charAt(0)

  1st call – reverseString("Hello")   will return   reverseString("ello")    + "h"
  2nd call – reverseString("ello")    will return   reverseString("llo")      + "e"
  3rd call – reverseString("llo")     will return   reverseString("lo")       + "l"
  4th call – reverseString("lo")      will return   reverseString("o")        + "l"
  5th call – reverseString("o")       will return   reverseString("")          + "o"

Second part of the recursion method

  The method hits the if condition and the most highly nested call returns immediately

  5th call will return reverseString("") + "o" = "o"
  4th call will return reverseString("o") + "l" = "o" + "l"
  3rd call will return reverseString("lo") + "l" = "o" + "l" + "l"
  2nd call will return reverserString("llo") + "e" = "o" + "l" + "l" + "e"
  1st call will return reverserString("ello") + "h" = "o" + "l" + "l" + "e" + "h"

In the end we get the reversed string.

So this one was heavy and I doubt if someone could come up with this solution on his own in interview. If you don't understand this solution right now its totally fine.

Now continuing on our tradition from above, here's the shortened version of above code using arrow functions and ternary operators.

const reversedString = str => (str === "") ? "" : reverseString(str.substr(1)) + str.charAt(0);

Parting words

Hope you learned something from the article. Reversing a string is a simple problem which can be useful in solving more complex problems in interview or maybe if you are lucky enough you'll be asked just to reverse a string ;)

See you in next post, till then Happy Coding!

#javascript#algorithms#interview
 
Share this