DEV Community

Tadea Simunovic
Tadea Simunovic

Posted on

How to string.reverse('javascript')

As I preparing for upcoming technical interviews after some research, reversing a string is one of the common challenges.

reverse() is a built-in function included with the most recent javascript versions. The alone word says that it will reverse all elements within a given array.

Challenge

Given a string, return a new string with the reversed order of characters

Solution 1

In order to reverse a string with reverse(), we can use a method to reverse string into an array first, call reverse() method on it and turn it back into the string. Take a look at the flow diagram below with the result code.
Alt Text
There is also a version where you can chain all three methods together.

Alt Text

Solution 2

Here we will use for...of loop, it loops through a block of code a number of times. I will be using the syntax that was introduced with ES2015

Let's take a look at the diagram again and result.
Alt Text
So after I create an empty variable, I will declare a temporary variable that is redeclared every single time through this loop of character, then keyword of, string, in this case, str is object whose iterable properties are iterated(all characters of string).
So we're going to iterate through each character of string one by one and set each character equal to this temporary variable character.
We then take that character added on to the start of the string reversed and then after the entire for loop we return the string reversed.

Iteration behind a scene

Alt Text

Hint! If you need to loop through every so many-elements within the array, then you do have to go back to using a for loop or even a while loop for that matter.

There are plenty more ways how to reverse strings in Javascript. I found these two easy to understand and use.

Top comments (0)