My Development Notes

Programming Made Easier


Reversing a string in JavaScript – Explanation

Say you want to reverse a string passed in a JavaScript functionality as below:

elephant => tnahpele
Hello => olleH

There are various ways to reverse the string passed above. Let’s look at them and break them down for you to understand.

So the first and the most popular method used to achieve the reverse string functionality is using the split-reverse-join method. Here’s the example :

function reverseStr(animalName) {
  return animalName.split("").reverse().join("");
}
reverseStr("Elephant");

// outputs 'tnahpelE'

Let’s break down in detail the above code syntax to see how this piece of code above actually works behind the curtains. So, when we first use the split() method with the string it splits the original string into an array of substrings like this:

function reverseStr(animalName) {
  return animalName.split("");
}
reverseStr("Elephant");

//outputs ['E', 'l', 'e', 'p', 'h', 'a', 'n', 't']

Notice that since we’ve used (” “) as separator, the string is split between words. Now we use the next method which is reverse() and see what happens next:

function reverseStr(animalName) {
  return animalName.split("").reverse();
}
reverseStr("Elephant");

//outputs ['t', 'n', 'a', 'h', 'p', 'e', 'l', 'E']

You can clearly see that now all the alphabets reverses. Notice that we haven’t used (” “) and instead used reverse() otherwise the code won’t work as expected.

Finally we add .join(“”) to combine the alphabets to get the final output which is "tnahpelE for Elephant.

You can also use an arrow function to achieve the same result like the below example:

const reverseStr = animalName => animalName.split('').reverse().join('');

reverseStr('cat');

// outputs 'tac'

Here’s another code to achieve the same result using spread operator:

const reverseStr = animalName => [...animalName].reverse().join('');

reverseStr('giraffe');

// outputs 'effarig'

Posted

in

by

Leave a Reply