1️⃣ 4 Ways to Reverse a String in JavaScript ⏪ (Beginner-Friendly)

Alena Silverbush
5 min readSep 11, 2020

--

There’s no denying that you need to know basic data structures and algorithms to be a good developer. Today I’d like to start a series of blogs dedicated to discussing those topics for anyone who’s just beginning with JavaScript and for my own sake. I believe writing about concepts solidifies them in my brain and helps me understand them on a better level. The first one is a classic JavaScript interview question, especially for junior developers — Reverse a String ⏪. Since in JavaScript there are always a few ways to solve problems we will look at a few possible examples. So let’s see how can we solve this challenge!

Challenge

Write a function that takes in a string as an argument and prints out to the console that string in reversed order 👉

Solutions

Method 1. Built-In Method ⏪

First of all, we can try to find a built-in method to help us solve this challenge, something like .reverse(). After a quick research, we will discover that there’s no built-in method like that for strings in JavaScript. However, there is one for arrays. So to be able to use this built-in method we’ll have to transform our string into an array first. Let me give you a step by step guide of this approach:

  • Step1 — Transform the string into an array with .split()
  • Step2 — Reverse the items of the array with .reverse()
  • Step3 — Join back all the elements of the array into a string with .join()

Let’s see how all this will look in code 👉

One important note about .split() and .join() — both those methods take in a parameter of separator. In our case, we put a single set of quotes because we ultimately want each character to be its own element of the array. If we wanted each word to be its own element — put a space in between quotes — .split(“ ”) and .join(“ ”).

We can make this code even cleaner by eliminating all the unnecessary variables and instead use a technique called “chaining methods” — calling one method after another on an object, in one continuous line of code 👉

Voila! We solved the challenge! All of our code fits on one line what can be more perfect and satisfying than that! 😌 Not to discourage you, but interviewers would probably not be so interested in this approach and usually, they will ask you to solve this challenge without using built-in methods. Which brings us to the second approach.

Method 2. Decrementing for loop ⏪

The second approach is a bit more complicated and tedious and requires the knowledge of for loops in JavaScript, so let’s dive right in!

With decrementing for loop we will loop through our string starting at the end in descending order (thus decrementing) and on each iteration, we will save the index of the value of our current string into our new string that will start empty but will be populated with letters in reversed order. I feel like that is quite confusing so let’s see the code for that 👉

What is happening here? Let’s once again break this down into logical steps:

  • Step1 — initialize a variable that equals to an empty string (it will host our reversed string later and this is what we’re outputting in the console)
  • Step2 — create a for loop that takes 3 arguments: the first one tells our loop where to begin, which in our case is at the end (because we’re going in descending order). We’re subtracting 1 out of the length of our string because the length is always going to be 1 count more simply because arrays start at index [0], so what we’re doing is telling the loop to start at the last letter — x in our case. The second argument tells the loop for how long it should run, in our case it should run until i (or index of the array) is more than or equal to zero. This is where the loop will end. The third argument is the decrementer — we’re going to subtract one from i each time the loop runs.
  • Step3 — in the body of our loop we write the code we want to execute on each iteration of the loop. Here we’ll set the variable we created earlier (that was empty) to equal to the index [i] of our string. This way on the first iteration of the loop our empty string will equal to x, on the second it will equal to xo, on the third, it will equal to xof and so forth until the end of the string.

Also just in case, anyone was wondering the time complexity of this algorithm it is O(n) — linear time complexity! Because the loop will execute as many times as the number of elements in the array. The running time increases at most linearly with the size of the input 👉

Method 3. Incrementing for loop

This one is similar to the one before but instead of starting at the end and decrementing, we will start at the beginning of the string and increment [i] for as long as i is less than the length of the array. We also need to switch the order in the body of our loop. Instead of 👉 $ reversedStr = reversedStr + string[i] we’ll do 👉 $ reversedStr = string[i] + reversedStr 👉 and we’ll get the same result!

Writing both those for loops you’re more likely to make a mistake and there’s just so many things that can go wrong. Our next method is better and easier to remember and understand and it’s actually a part of ES6 syntax.

Method 4. for… of loop (ES6) ⏪

The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

The main difference of this particular loop is that it takes the value of an element of an array instead of just its index and performs an iteration on each value of each element of the provided string. So this says: for each character (char) of the string save the value into new reversedStr. It basically is doing the same job as our loops above, just more elegantly in my opinion!

There you have it! Four ways to reverse a string in JavaScript! I have to be honest, there are other methods we can use but maybe I’ll tell you about them in my next blog! Thanks 🤓

Resources

--

--