I’m back with a new Free Code Camp Challenge today: reverse a string. This time, we must write a function that takes a string and returns it in… wait for it…
…reverse order.
There are a few solutions to this problem; some of them are obvious to anyone with prior experience with Array methods, but those less versed in them may take an iterative approach. I’ll be showing both methods to reverse a string, starting up with the iterative function:
function reverseString(str) { var newStr = ""; for (var i = str.length - 1; i >= 0; i--) { newStr += str[i]; } return newStr; } reverseString('hello'); //--> olleh
This function is pretty simple. It takes a string, and loops through every character (starting from the end) as it adds it to a new string (newStr). It then returns this new variable, which should be the reversed version of our original string.
Next up, we’ll step it up and use a few Array methods to compress this code into a single line.
function reverseString(str) { return str.split('').reverse().join(''); } reverseString('hello'); // --> olleh
Wow! That was short!
Let me explain what’s going on: the first method, split() , will turn our string into an array, passing it an empty string as an argument ” will cause the string to be split at every character (if we give it a space, it will split the string at every space character etc.), so our string, ‘hello’, will become [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] .
The reverse() method does exactly that, it reverses an array and turns our array into [‘o’, ‘l’, ‘l’, ‘e’, ‘h’] .
Finally, join() will turn our array back into a string, the empty string passed as the argument will join the array without any characters in betweer array members: ‘olleh’. Giving it a ‘-‘ character would produce the following string: ‘o-l-l-e-h’.
So there’s the explanation for those unfamiliar with Array methods. As you can see, we can abstract code and produce a cleaner and easier to read solution, even if not always faster.