How to reverse a string in JavaScript.

ham_codes
3 min readJan 31, 2021

Lately I’ve been working on some JavaScript questions that I feel could possibly show up in technical interviews. One of the first things I worked on was how to reverse a string in JavaScript.

How do you set a string as a variable in JavaScript? We can use var, let and const. I won’t dive deep into the differences between these three, but let’s use one to get this started.

Now we have to try and get this string reversed. At first thought, many people might say to themselves, “wait, isn’t there a reverse() method in JavaScript?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

Couldn’t we just use that?” The answer isn’ that simple unfortunately.

The first thing we need to do is split up the string into separate smaller parts, that way we can work on each individual part. In order to do this we need the split() method that we have in JavaScript. According to the documentation this is how split is defined, “The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method’s call. ” So in order to get ready to reverse this person string, we need to first split it into this array. Below is what our string now looks like.

Once this string is split, we can now call the reverse() method on this string. So are we now done this problem? No we aren’t. Just calling reverse at this point would not return our original string, just reversed. Below is what our string now looks like.

We need to do one more thing to make sure our original string is returned, just in reverse order. There is one more method in JavaScript that we need to use. The join() method. By checking out the documentation we can see that the join() method is defined as such, “The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.” So we now need to take this array we created and make it a string again.

Our code will now look as follows:

I hope you liked this little dive into a way to reverse a string. There are other ways in which this can be done. That is one of the great things about JavaScript. Thanks for reading!

--

--