Quick Tech Tip – How to reverse a string with JavaScript

Being able to reverse a string is a useful skill and is often asked during programming related job interviews.

Let’s take a look at how strings can be reversed using JavaScript in today’s quick tech tip.

The first thing to consider is that JavaScript strings are immutable and cannot be reversed in place.

The reverse() method, or Array.prototype.reverse(), can reverse an array in place however.

We will convert the string to an array using the split() method. The split() method splits a String object into an array of strings by separating the string into substrings.

The reverse() method will reverse the array and output: [ ‘n’, ‘o’, ‘d’, ‘n’, ‘o’, ‘L’ ]

For the final step we will use the array prototype join() method to convert the array to a string and pass in the

parameter of a separator as ‘ ‘.
‘nodnoL’ is then printed in the console as our reversed string.

There are a few other ways to reverse a string in JavaScript and this is just one, and that concludes today’s tech tip.