In a recent job interview, I was asked to write a simple function that would reverse a string and return the result without using the in-build methods “reverse()”.

Reverse a string is one of the most frequently JavaScript questions in the technical round of interview. Interviewers may ask you to write different ways to reverse a string, or they may ask you to reverse a string without using in-build methods, or they may even ask you to reverse a string using recursion.

### Algorithm Challenge

Reverse the provided string.

You may need to turn the string into an array before you can reverse it.

Your result must be a string.

Provided test cases

reverseString(“hello”) should become “olleh”

reverseString(“Howdy”) should become “ydwoH”

reverseString(“Greetings from Earth” ) should return “htraE morf sgniteerG”

### Implementations

There are potentially tens of different ways to do it, excluding the built-in reverse function, as JavaScript does not have one.

### 1. Decrementing for-loop with concatenation

The original way that I achieved the intended result was to use a decrementing for-loop that appended each character of the input to a new string in reverse order. I was able to access the parsed strings of individual characters similar to the way you would reference an array’s items.

``````function reverse(s) {
let res = "";
for (let i = s.length - 1; i >= 0; i--) {
res += s[i];
}
return res;
}``````

### 2. Incrementing/decrementing for-loop with two arrays

Another way I formed to reverse a string was to create an empty array and iterate over the length of the string with both incrementing/decrementing counters. The array position uses the incrementing counter where as the parsed in string uses the decrementing one. Finally the created array is joined into a single string and returned.

``````function reverse(s) {
var res = [];
for (let i = s.length - 1, j = 0; i >= 0; i--, j++) {
res[j] = s[i];
}
return res.join("");
}``````

### 3. Incrementing for-loop with array pushing and charAt

The above example is a modification of the second example. Instead of using two counters however we use one incrementing value that gets deducted from the total length of the parsed in string. This calculated value determines the position of the next character to be pushed onto the new array (using the ‘push()’ function instead of ‘[]’). The other difference from the last example is that it uses the strings ‘charAt()’ method instead of its array capabilities.

``````function reverse(s) {
var res = [];
for (let i = 0, len = s.length; i <= len; i++) {
res.push(s.charAt(len - i));
}
return res.join("");
}``````

### 4. In-built functions

This implementation takes advantage of the ‘reverse()’ method provided by the Array prototype. First it splits the string into a real array, then calls the ‘reverse()’ method and finally returns the joined array.

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

### 5.  Decrementing while-loop with concatenation and substring

Using a decrementing while-loop I was able to implement this method. Again harnessing concatenation, I was able to achieve the iteration through the string in a similar fashion to the for-loop used in the first two examples. I was then able to use the strings ‘substring()’ function to retrieve each desired character.

``````function reverse(s) {
let len = s.length,
res = "";
while (len > 0) {
res += s.substring(len - 1, len);
len--;
}
return res;
}``````

### 6. Single for-loop declaration with concatenation

This is most likely my favorite implementation, due to its unnecessary cryptic nature. Using only a single for-loops parameters, I was able to decrement through the parsed in string and concatenate each character to a new string to return.

``````function reverse(s) {
for (let i = s.length - 1, res = ""; i >= 0; res += s[i--]) {}
return res;
}``````

### 7. Recursion with substring and charAt

The above example recursively calls itself, passing in the inputted string, excluding the first character on each iteration, which is instead appended to the result. Iterating through this process until no input is present (the base case) results in a reversed string.

``````function reverse(s) {
return s === "" ? "" : reverse(s.substr(1)) + s.charAt(0);
}``````

### 8. Internal function recursion

This is another example of using recursion to reverse a string. The implementation above uses an internal function, which is first called by the outer function, parsing in the inputted string, its length and an empty string. The internal function is then recursively called by itself until the string length has been decremented to zero – at which time the originally empty parsed in string has been concatenated with the inputted string characters in reverse.

``````function reverse(s) {
function rev(s, len, res) {
return len === 0 ? res : rev(s, --len, (res += s[len]));
}
return rev(s, s.length, "");
}``````

### 9. Half-index switch for-loop

I found this method to be a very effective way of reversing a string, highlighting its benefits when processing large strings. The strings half-point is first calculated and then iterated over. Upon each iteration the upper half’s value (calculated by deducting the current position by the string length) is temporary stored and replaced by the lower half’s value. The temporary value then replaces the lower half’s value to finally result in a reversed string.

``````function reverse(s) {
s = s.split("");
let len = s.length,
halfIndex = Math.floor(len / 2) - 1,
tmp;
for (let i = 0; i <= halfIndex; i++) {
tmp = s[len - i - 1];
s[len - i - 1] = s[i];
s[i] = tmp;
}
return s.join("");
}``````

### 10. Half-index recursion

The final method I wish to show uses the same ideology as the last implementation (half-indexing) but instead relies on recursion to reverse the string instead of a for-loop.

``````function reverse(s) {
if (s.length < 2) return s;
let halfIndex = Math.ceil(s.length / 2);
return reverse(s.substr(halfIndex)) + reverse(s.substr(0, halfIndex));
}``````

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.