String Reversal In Javascript

Photo by Tyler Nix on Unsplash

There are a bunch of ways to reverse a string in Javascript.

I’ve got a big mug of coffee next to me while writing this and it’s inspiring me. Let’s reverse the string, “coffee”. Here’s how to do it with magical built-in methods:

Let’s break that down.

The #split method turns a string into an array.

In order to reverse each letter in the string, we have to pass #split an empty string argument (“”). This splits the string between each character.

We can then chain the #reverse method and that will reverse all of the elements in the array.

Now the string is reversed but it’s still an array. How can we return a string? The #join method will turn an array into a string, so we’ll add that to the end of our method chain.

Similar to #split we need to pass in an empty string argument to #join so our array elements will be joined in-between characters.

Awesome! Our string is reversed! In an interview setting, you might be asked to reverse a string without using built-in methods. Let’s solve that problem next.

Here’s our reverse function. I’ve included a reversedString variable that we’ll return at the end.

Now we need to iterate over our string. I like the JS for/of statement because it’s short and readable.

Inside of our loop, we can concatenate to reversedString by adding char to the front.

Keeping up with our string being “coffee”, the first time through our loop char = “c”, the next time char = “o”, and so on.

When the loop exits our reversedString will be built and we return it at the end of the function. Here’s the whole thing put together.

It even works with spaces!

Thanks for reading!

Full Stack Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store