Reverse a String

In this freeCodeCamp algorithm, we need to take a given String and then reverse it while making sure the result also returns a String.

Hint: Convert the string into an array before reversing it.

Requirements

  • reverseString("hello") should return a string
  • reverseString("hello") should become "olleh"
  • reverseString("Howdy") should become "ydwoH"
  • reverseString("Greetings from Earth") should become "htraE morf sgniteerG"

Psuedocode

If we break the problem down into smaller pieces, the requirements ultimately look something like this:

// Take a string
    // Split the string into an array
    // Reverse the items in the array
    // Join the items back together
    // Return the reversed string

Reading the Docs

Great developers are often very resourceful. Given that just about all of the programming information you could imagine is already online, chances are you should be able to find the answers to your questions fairly quickly.

If you're not already familiar with the Mozilla Developer Network then it's about time you bookmark it.

MDN is the resource of all resources for JavaScript. I mean, the dude who co-founded Mozilla actually invented JavaScript.

.split(), .reverse(), and .join()

In our pseuedocode, we noted that we needed a way to split the string up, ideally into individual characters. Lucky for us, JavaScript already has a built in method that will allow us to do this.

Here are a few resources on how to use the .split(), .reverse(), and .join() method:

String.prototype.split()
Array.prototype.reverse()
Array.prototype.join()

Solving the Algorithm

Create the Function

First, let's start by creating the function that will accept an argument str, that will get passed through and returned as the reverse.

function reverseString(str) {

};

Using the String.split() Method

Next we can setup our function to utilize the .split() method we learned about from the MDN Docs. This allows us to split the inputted string, and return it as an array.

function reverseString(str) {
   
   // Passing an empty string splits the string at each character
    var splitStr = str.split('');
    
    return splitStr; 
};

reverseString('hello'); // Outputs: ["h", "e", "l", "l", "o"]

Using the Array.reverse() Method

Next we'll use the .reverse() method which, hence the name, allows us to reverse an array.

function reverseString(str) {
    // Passing an empty string splits the string at each character
    var splitStr = str.split('');
    
    // Reverse the characters in the array
    var reverseArr = splitStr.reverse();
    
    return reverseArr;
};

reverseString('hello'); // Output: ["o", "l", "l", "e", "h"]

Using the Array.join() Method

Lastly, let's take a look at the .join() method where we can take the items of an array and join them together to output a String.

function reverseString(str) {
    // Passing an empty string splits the string at each character
    var splitStr = str.split('');
    
    // Reverse the characters in the array
    var reverseArr = splitStr.reverse();
    
    // Join the characters in the array to form a string
    var reversedString = reverseArr.join('');
    
    return reversedString;
};

reverseString('hello'); // Output: "olleh"

And there it is!
Using methods that are built in to the JavaScript library we're able to reverse a string! Pretty cool, huh?

Refactoring

All in all, we were able to get the job done with only a few lines of code. The fact of the matter is that even though our solution was only a few lines of code, we can refactor this down to a one liner by using chaining. Let's take a look:

function reverseString(str) {
    return str.split('').reverse().join('');  // Output: "olleh"
};

reverseString('hello');

Bonus Solution

Let's take a look at how we can solve this algorithm if we didn't have access to the .reverse() method:

function reverseString(str) {
  var reverseArr = [];

  str.split(''); // Split str into an array

  for (letter in str) { // Loop through each character in str
    reverseArr.unshift(str[letter]); // Add each character to front of reverseArr
  }

  return reverseArr.join(''); // Convert reverseArr to string
}

reverseString("hello"); // Output: "olleh"

Wrapping Up

Hopefully you found this to be a helpful walkthrough of this freeCodeCamp algorithm on how to reverse a string!

Shoot me an email at tim@timwheeler.com with any questions and if you enjoyed this, stay tuned and subscribe below! 👇