# String Reversal Algorithm in Javascript

I am following the FreeCodeCamp curriculum and I decided that I will blog what I learn in the process, so I can have a look at those in the future and feel proud that I have blogged a lot and I should continue it because its awesome. So today we will see how to reverse a string using Javascript.

Okay so let’s get into programmer mode.

Today I solved Reverse a string challenge on FCC.

Below, at first I will provide my code to show how I solved the challenge, explain it and after that discuss other methods of solving the problem.

So here is my code.

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

What my code does is it first uses the split function which splits the passed string object into array of strings by seperating 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 submitted my solution and it passed all the tests and took me to the next challenge.

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

To make my above solution shorter we can chain methods like as,

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

## Reversing a string by using for loop

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

``````function reverseString(str) {
let newString = "";
for(i = str.length - 1; i&gt;=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 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.

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

Aand in the last we returned the reversed string.

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

Now the third method…

## Reversing a string by using Recursion

For this solution, we 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"
```

So the 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);
/*
First Part of the recursion method
You need to remember that you won’t have just one call, you’ll have several nested calls
Each call: str === "?"        	                  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"
*/
}
reverseString("hello");``````

Explaination is given in the code.
Okay so that one was heavy. You can always ask in comments.That’s my favourite method too.

The same above method using ternary operators.

``````function reverseString(str) {
return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}
reverseString("hello");
``````

### Last words

Reversing a String in JavaScript is a small and simple algorithm that can be asked on a technical phone screening or a technical interview. You could take the short route in solving this problem, or take the approach by solving it with recursion or even more complex solutions.

I’ll see you again in next post, till then happy reversing! 😍

Share #### Jalaj

A student, a learner, constantly learning new things and have great interest in programming and web development.

This site uses Akismet to reduce spam. Learn how your comment data is processed.