DEV Community 👩‍💻👨‍💻

Cover image for Reverse String In JavaScript  By 4 Approach
Adnan Aslam
Adnan Aslam

Posted on

Reverse String In JavaScript By 4 Approach

Alt Text

Here, you can see that how can you reverse string in different ways.

This is a very common question in interview if you are going to give for front end position.

Before start you have to think a little about the approach of that how can you do this so that first think you decide in your mind as think one string as "coding", Now you have to think to reverse this it will become "gnidoc".

Now as you thought that this ("coding" => "gnidoc") is the one that you want to do where you think of a string and reverse that from last character to the first.

  1. Using Built-In Functions

If you are using built-in function to reverse a string in javascript there you have to use split(), reverse() and join() in the combination from one after the other.

Alt Text

Here you have seen the built-in functions to reverser the string by normal function but you can make your code precise by using arrow functions.

Alt Text

With Arrow Function you can write the code in one line as you can see above here you can use console.log(Solution("coders")) to print the result in you console.

  1. Using Recursion

Here we use two methods to make the function call recursively before that you have to think a little that what recursion is and you can achieve your goal by using recursion.

Recursion : This occurs "when a function call itself" now you are thinking how so as you can see in below code

Alt Text

Here you can see that the recursion() inside the function is a recursive function.

Now lets move how we can reverse a string using recursion so for that you have to use two methods from javascript that are substr() and charAt().

Alt Text

substr() returns the characters from beginning in the string as above you can see.

Alt Text

chartAt(), it returns the character from a string from where you want.

Now, its time to write a program to reverse a string by recursion

Alt Text

For other two methods you can go to my github account and see how I have used Brute first Approach(that is using for loop) and by stack method(using push() and pop() methods) you can reverse a string.

Note: It's not the way you are making thing happen it depends how well you can do that.

Follow me on Github :


Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!