Sorting & Reversing Strings in JavaScript

Elijah Wines
6 min readNov 3, 2022

--

A common coding interview question you may get is “How do you sort a string?”, or maybe, “How do you reverse a string?”. It’s important to know the answer to these questions, as working and manipulating strings is a very common coding practice. Being able to answer these questions will mean that you understand fundamental coding concepts. They can also help you get started with algorithms.

Today, I will discuss multiples ways that we can both sort and reverse strings in JavaScript. There are built-in JavaScript methods that can accomplish these tasks easily, which we will certainly cover, but it’s also good to know whats going on under the hood so we can better understand these coding concepts. Let’s start off with sorting strings.

Sort a String

Sorting a String With .sort()

Our goal here is to take a string and sort it in alphabetical order.

// examplevar letters = "gfedcba";// turn 'letters' into 'abcdefg'

We can start off by using the built-in ‘.sort()’ method.

var sortString = (string) => {
return string.split("").sort().join("");
};
sortString(letters);
// returns "abcdefg"

Let’s walk through what happened here:

  1. We take the string argument and split it into an array. We have to do this because the ‘.sort()’ method can only be called on arrays, not strings
  2. We then call the ‘.sort()’ method on the array
  3. We join the sorted array back together and return it

This method for sorting our string is quick and simple with the use of the built in ‘.sort()’ method, along with ‘.split()’ and ‘.join()’.

Now that we’ve solved the problem using a built-in JS method, lets dive a bit deeper and solve the problem using a for loop.

Sorting a String With a For Loop

var sortString = (string) => {
var arr = string.split("");
var temp;
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
};
};
};
return arr.join("");
}
sortString(letters);
// returns "abcdefg"

Let’s break this down:

  1. We take our string argument and split it into an array called ‘arr’
  2. We then declare a variable called ‘temp’ that will be used later on
  3. We start a regular for loop to iterate through ‘arr’. We will refer to this as our “first loop”
  4. We then begin another for loop within our first loop where ‘j’ will always be 1 index higher than the ‘i’ variable that we declared in our first for loop. We will refer to this as our “second loop”
  5. within our second loop, we create an if statement that determines whether or not our first loops ‘i’ index in the array is greater than our second for loops ‘j’ index in our array
  6. if the ‘i’ index of the array is greater than the ‘j’ index in our array (in other words, if the next letter in the array comes before the original letter in the alphabet), we then swap ‘arr[i]’ with ‘arr[j]’
  7. steps 4–6 will repeat for every letter in ‘arr’, comparing every letter to the letter of the current index
  8. Once every letter in ‘arr’ has been evaluated with every other letter in ‘arr’, we then join ‘arr’ together into one string and return the value

This is definitely a tough concept to grasp, but ultimately, this is what goes on under the hood in the ‘.sort()’ method, and is important to know in order to gain a deeper understanding of algorithmic concepts.

Reversing a String

Our goal in this section will be to put a string in reverse order.

var word = "hello";// we want this to become 'olleh'

Reverse a string using .reverse()

We will start off using our built-in ‘.reverse()’ JavaScript method.

var reverseString = (string) => {
return string.split("").reverse().join("");
};
reverseString(word);
// returns "olleh"

This solution is very similar to our sorting solution using the built-in method ‘.sort()’. Instead of sorting, we just use our ‘.reverse()’ method.

  1. We split the string into an array
  2. We then call the ‘.reverse()’ method which reverses the string for us
  3. We then join the array back together and return our reversed string

This is definitely the quickest and easiest way to reverse our string, but again, we will need to dive deeper to find out whats really going on here.

Lets take a look at another way we can solve this problem, but this time we will use a decrementing for loop.

var reverseString = (string) => {
var reversed = "";
for (var i = string.length - 1; i >= 0; i--) {
reversed += string[i]
};
return reversed;
};
reverseString(word);
// returns "olleh"

Lets break this solution down:

  1. We declare a new, empty string called ‘reversed’
  2. We then begin our decrementing for loop. This is different than your typical for loop because instead of starting the loop at the beginning of the string, we start our loop at the end of the string and iterate through it backwards
  3. While going through the loop, we add each letter of the string to our ‘reversed’ string

This is a great way to reverse a string because its not that tough of a concept to grasp, and it is solved in only a couple lines of code. The next method of reversing the string will involve a tougher concept, recursion.

Reversing a string using recursion

A recursive function is a function that calls itself until the desired output is reached. Lets take a look at how we can reverse a string using a recursive function.

var reverseString = (string) => {
if (string === "") {
return "";
} else {
return reverseString(string.substr(1)) + string.charAt(0);
};
};
reverseString(word);
// returns "olleh"

Let’s break down what happens here:

  1. We use an if else statement to begin. If the string is empty, that means we have reached the end of our algorithm and we return nothing.
  2. if the string is not empty, we then return two things:

— the reverseString function, but this time we call it with every letter in the given string argument except the first letter PLUS the first letter of the given string

steps 1 and 2 are then called repeatedly until we hit the end of the string, which will then return our string in reverse order.

Much like our nested for loop used in the sorting section of this article, this is a tough concept to grasp. Not only is string manipulation common, but so is the concept of recursion. If you’d like to get an in depth look of how our recursive string sorting function works you can easily throw in some console.logs to see what happens to the string step by step.

Conclusion

In this article, we took a look at multiple ways that we can both sort and reverse strings using JavaScript. We looked at the easy way, and we looked at the hard way. I hope you find value in learning the hard way because ultimately it’ll help you learn the deeper concepts of programming. Often times we are spoiled with the variety of technologies that are handed to us in todays world of programming. Although it isn’t always fun, I believe it is important to take a hard look at the fundamentals of programming so that we can all grow as developers. This way, we are equipped with the abilities that can help us build something greater so that the developers of the future are even more spoiled than we are!

I hope you have enjoyed this article, and happy coding!

--

--

Elijah Wines

Software Engineer - JavaScript, Ruby, React, Ruby on Rails