Tutorial: Learn how to reverse a string in Javascript

·

5 min read

The goal of this Tutorial is to help you understand how to reverse a string in Javascript. You’ll learn different ways to solve this problem. This is one of the best ways to learn how to solve a problem.

Before you start solving this problem, you will need to familiarise yourself with basic Javascript.

By the end of the Tutorial, you will:

  • Know how to convert a string into an array and convert an array into a string
  • Know how to use Javascript build in methods such as: reverse() and join()
  • Know how to loop through a string in reverse order using a for loop.
  • Know how to concatenate a string.
  • Know how to use reduce() (higher order array function)

Problem Solving

In order to become a good programmer one needs to be a good problem solver because at the end of the day that is what a developer’s real job is to solve problems. It is one of the main skills that employers seek in job applicants.

Following are some ways we can solve a problem:

  1. The first step to solve a problem is to properly understand the problem. Understanding the problem will help you craft a better solution.
  2. Once you have understood the problem, implement a plan to solve the problem. Do not just jump into coding the solution yet. Take appropriate time to craft the solution.
  3. Once you have a plan. Execute the plan. Plan execution involves the actual coding.
  4. Review your solution. Once a problem has been solved, always look to see if the solution can get better.

Solution #1

Javascript already has a built in method reverse() that reverses the order of the elements in an array. However, we need to reverse a string and the reverse() method can not be used on a string.

In order to use the reverse() method, we need to make sure we are working with an array. So the first step of this solution is to convert the string into an array which can be achieved by using a Javascript string method split().

split() method converts a string into an array of characters and returns a new array.A variable named strArr will store the array of characters. Now that we have an array, we can use the reverse() method on this array which will give us the array in reverse order and store the result in a variable named reversedArr.

   // convert the string into an array of characters
   const strArr = str.split("")

   // reverse the array using reverse method
   const reverseArr = strArr.reverse()

The final step is to convert the reversedArr array into a string which can be achieved using join() method and return the final result.

join() method returns an array as a string.

    const result = reverseArr.join("")
    return result

Final Code

function reverse(str) {
    // convert the string into an array of characters
    const strArr = str.split("")

    // reverse the array using reverse method
    const reverseArr = strArr.reverse()

    // convert  the array back to a string using built join method
    const result = reverseArr.join("")
    return result

}

reverse("hello")

If you are familiar with modern Javascript syntax. We can have a one line solution to this problem using an Arrow Function.

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

Solution #2

Since strings in Javascript are both iterable and have number indexes and length just like an array, we are able to loop through them using for loop.

First step to this solution is to create a variable named result and initially it will be set to an empty string.

const reversed = ""

Using the for loop, iterate through the given str value and take out one character of the string at a time and stick it at the start of the variable named result.

for (let i = 0; i < str.length; i++) {
       reversed = str[i]  + reversed
 }

Finally return the result variable.

function reverse(str) {
   const reversed = ""

   for (let i = 0; i < str.length; i++) {
       reversed = str[i]  + reversed
   }

   return result

}

reverse("hello")

Solution #3

Similar to what we did on our first solution, the first step will be to convert the string into an array because reduce can only be used on an array. With the edition of ES6 there are multiple ways to achieve this task. One such instance is using the spread operator.

const strArr = [...str]

The next step is to make use of the reduce() method. It takes two sets of arguments, one being an arrow function and the other being the initial value for our function. In our case the initial value will be an empty string “”.

The arrow function will have two arguments:

  • previousValue - it accumulates the arrow function’s return values
  • currentValue - The current element from the array.
const result = strArr.reduce((reversed, char) => {
      return  char  + reversed
}, "")

Since we are passing in the initial value the first time the function runs, the initial value will be used in place of previousValue. Similar to our second solution, stick the character to the start of the previousValue in every iteration and return the result.

Conclusion

Hope you find this article helpful. Pleas feel free to comment your suggestion, feedback or your version of solution to this problem.