Writing a function to reverse a string is one of the most frequently asked questions in a JavaScript interview especially if you are a junior software engineer. The interviewer may ask you to write reverse string function in different ways such as using for loop, using recursion, or without using built-in methods, etc.

In this tutorial, we will discuss 4 different ways to reverse a string in JavaScript.

1. JavaScript Built-in Methods

The best way to reverse a string is using three different JavaScript built-in methods: split(), reverse() and join().

  • split() - It splits a string into an array of substrings using a separator, and returns the new array.
  • reverse() - This method reverses the order the elements in an array. The first element becomes the last and the element becomes the first.
  • join() - It joins all elements of an array into a string, and returns the new string.
const reverseString = (str) => {
    return str.split('').reverse().join('');
};

reverseString('hello world!');
// => !dlrow olleh

2. for Loop

Reversing a string using for loop may seem a naive approach but it works well. We can use decrementing (or even incrementing) loop to iterate over each character of the string and create a new reversed string:

const reverseString = (str) => {
    let reversed = '';
    for (let i = str.length - 1; i >= 0; i--) {
        reversed += str[i];
    }
    return reversed;
};

reverseString('hello world!');
// => !dlrow olleh

A modern for loop syntax using ES6 for ... of:

const reverseString = (str) => {
    let reversed = '';
    for (const c of str) {
        reversed = c + reversed;
    }
    return reversed;
};

3. Recursion

Recursion is another way to reverse a string in JavaScript. This approach involves two JavaScript functions: substr() and charAt(). The first method returns a substring of a string and the second method returns the specified character of a string.

const reverseString = (str) => {
    return str ? reverseString(str.substr(1)) + str[0] : str;
};

reverseString('hello world!');
// => !dlrow olleh

The number of times, the recursive function is called, depends on the length of the string. It will become really slow if the string is very long. So this is not a very good solution but still a way to solve the challenge.

4. reduce() Method for Arrays

Another rarely used approach to reverse a string in JavaScript is using reduce() function of arrays. This method reduces the array to a single value. Since this function works for arrays, we first need to split the string into an array using split() method.

const reverseString = (str) => {
    return str.split('').reduce((r, c)=> c + r, '');
};

reverseString('hello world!');
// => !dlrow olleh

Summary

There are tons of different ways to reverse a string in JavaScript. In this tutorial, we have discussed 4 different approaches to solve the reverse string challenge:

  • Using built-in JavaScript functions like split(), reverse(), and slice(). It is straightforward and perhaps the best approach.
  • Using for loop to iterate over all characters of a string and create a new reversed string.
  • Recursively convert the string into a substring until the empty string is reached, and then combine them to form a reversed string. It may become very slow if the string is large.
  • Splitting the string into an array and then reduce the array into a single value using arrays' reduce() function.

If you have any question or want to share your feedback, please feel free to send me a tweet anytime.

Happy Coding 😍

Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV.

πŸ™Œ Join the weekly newsletter and get the latest tutorials from my blog and around the internet.
No spam, ever. You can unsubscribe anytime.

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.